12
\$\begingroup\$

Inspiration: Leetcode's [3Sum] link

Problem

Given an array nums of n (not necessarily distinct) integers, and given a target number target, return an array of all of the unique quintuplets [nums[a],nums[b],nums[c],nums[d],nums[e]] such that the following conditions are held:

  1. 0 <= a,b,c,d,e < n (or 1 <= a,b,c,d,e <= n if using 1-indexing)
  2. All of a,b,c,d,e are distinct.
  3. nums[a] + nums[b] + nums[c] + nums[d] + nums[e] = target
    • In the case of multiple arrays, we also add the requirements that at least two values in each of the arrays are distinct.

If all 3 conditions cannot be satisfied, you can return a junk value of your liking, or just an empty array [[]]. The testcases down below will use -1 as the specified junk value.

You may return the answer in any order. For example, given the array [-5,-2,-2,1,3,4,6] and target 0, you could return any permutation of [[-5,-2,-2,3,6]]. You do not need to return all possible permutations of one single array.

Testcases:

# Note: Thank you all for the additional test cases! However, # I will not be taking any more at this time just so the # question doesn't appear on the [Home] page for too long. 
 Array: [-5,-2,-2,1,3,4,6] Target: 0 Output: [[-5,-2,-2,3,6]] Array: [-5,-4,-2,0,1,2,6] Target: 1 Output: [[-5,-2,0,2,6],[-4,-2,0,1,6]] # Note that outputting `[[-4,-2,0,1,6],[-5,-2,0,2,6]]` is also valid, # although returning just `[[-4,-2,0,1,6]]` or `[[-5,-2,0,2,6]]` is not. Array: [0,-1,2,3] Target: 4 Output: -1 Array: [0,1,-9,6,7] Target: 6 Output: -1 Array: [0,1,9,9,5] Target: 45 Output: -1 Array: [1,4,6,9,-4] Target: 16 Output: [[1,4,6,9,-4]] Array: [1,0,9,6,5,0] Target: 21 Output: [[1,0,9,6,5]] Array: [1,0,9,6,5,4,7] Target: 21 Output: [[1,0,9,6,5],[1,0,9,4,7]] Array: [1,0,9,6,5,4,4,7] Target: 21 Output: [[1,0,9,6,5],[1,0,9,4,7],[0,6,4,4,7],[1,5,4,4,7]] # Above test case suggested by @Shaggy Array: [1,1,2,2,3,3,4,4] Target: 11 Output: [[1,2,2,3,3],[1,1,2,3,4]] # Above test case suggested by @Arnauld 

This is , so the shortest solution wins!

\$\endgroup\$
10
  • \$\begingroup\$ Suggested test case: [1,0,9,6,5,4,4,7], 21. \$\endgroup\$ Commented Dec 10, 2024 at 21:44
  • \$\begingroup\$ @Shaggy Added . \$\endgroup\$ Commented Dec 10, 2024 at 22:06
  • \$\begingroup\$ What's the source for this problem? \$\endgroup\$ Commented Dec 10, 2024 at 22:09
  • \$\begingroup\$ @xnor Sorry, should've added that. My inspiration for this was from Leetcode's "3Sum" problem. \$\endgroup\$ Commented Dec 10, 2024 at 22:12
  • 1
    \$\begingroup\$ Suggested test case: [1,1,2,2,3,3,4,4], 11 \$\endgroup\$ Commented Dec 11, 2024 at 0:53

22 Answers 22

4
\$\begingroup\$

Vyxal, 8 bytes

s5ḋU'∑⁰= 

Try it Online!

-2 from emanresu

Takes list then target.

Explained

s5ḋU'∑⁰=­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­ s # ‎⁡Sort the input. This helps with uniquification later 5ḋ # ‎⁢Get all combinations without replacement of length 5 U # ‎⁣Filter out duplicate instances of combinations ' # ‎⁤Keep combinations where: ∑ = # ‎⁢⁡ The sum equals ⁰ # ‎⁢⁢ The target 💎 

Created with the help of Luminespire.

\$\endgroup\$
4
  • \$\begingroup\$ @Arnauld I allow it to be 0-indexed or 1-indexed. \$\endgroup\$ Commented Dec 10, 2024 at 22:56
  • \$\begingroup\$ @Arnauld I don't see why it wouldn't, regardless of 0 or 1 indexing. \$\endgroup\$ Commented Dec 10, 2024 at 23:40
  • 1
    \$\begingroup\$ @Arnauld "You may return the answer in any order. For example, given the array [-5,-2,-2,1,3,4,6] and target 0, you could return any permutation of [[-5,-2,-2,3,6]]." \$\endgroup\$ Commented Dec 10, 2024 at 23:48
  • \$\begingroup\$ My bad. I was reading the 1st condition as 0 <= a<b<c<d<e < n from the beginning. \$\endgroup\$ Commented Dec 11, 2024 at 8:01
4
\$\begingroup\$

Python 3, 95 bytes

f=lambda t,a,*p:[p][t*t:len(p)==5]or{i for v in[*a]for i in f(t-a.pop(0),[*a],*sorted([*p,v]))} 

Try it online!

Input target value and the array of nums, output a set of tuples.

\$\endgroup\$
3
\$\begingroup\$

Charcoal, 57 bytes

W⁻θυF№θ⌊ι⊞υ⌊ι≔⟦⟧θFEX²LυE⌕A⮌⍘ι²1§υλF⁼⁵LιF⁼ηΣιF¬№θι⊞θιEθ⭆¹ι 

Try it online! Link is to verbose version of code. Explanation:

W⁻θυF№θ⌊ι⊞υ⌊ι 

Sort the input list.

≔⟦⟧θ 

Start with no results.

FEX²LυE⌕A⮌⍘ι²1§υλ 

Get all subsets of the sorted list.

F⁼⁵Lι 

Filter on those that have length 5.

F⁼ηΣι 

Filter on those with the desired total.

F¬№θι 

Filter on those that are distinct.

⊞θι 

Keep only the distinct subsets of 5 with the correct total.

Eθ⭆¹ι 

Pretty-print the found subsets.

\$\endgroup\$
3
\$\begingroup\$

Jalapeño, 7 bytes

cₓ5u↥{Σ= 

Explained

cₓ5u↥{Σ= cₓ5 # Choices of length 5 of implicit input u # Unique only ↥{ # Where Σ= # Sum is equal to implicit second input 

Hex-Dump of Bytecode

 0 1 2 3 4 5 6 7 8 9 A B C D E F 0000: e8 35 e4 d1 c4 e9 59 

Try it Online!

\$\endgroup\$
2
  • \$\begingroup\$ This returns duplicate 5tuples for [1,0,9,6,5,4,4,7], 21 \$\endgroup\$ Commented Feb 4 at 8:13
  • \$\begingroup\$ @lyxal Ah rats, patched. \$\endgroup\$ Commented Feb 4 at 20:06
2
\$\begingroup\$

Vyxal, 20 bytes

→tṖƛ5Þİ_;'∑←t=;λsS;ε 

First Vyxal submission 🎉 Almost certainly golf-able.

Explained

→t # Assign the target to t Ṗ # Get all permutations of the input list ƛ5Þİ_; # Taking the first 5 elements of each permutation '∑←t=; # Where the sum is equal to t λsS;ε # Uniqueify by the sorted string 

Try it Online!

\$\endgroup\$
2
\$\begingroup\$

Uiua, 11 bytes

◴▽=⤚≡/+⧅<5⍆ 

Try it!

◴▽=⤚≡/+⧅<5⍆ ⍆ # sort ⧅<5 # get quintuples ▽=⤚≡/+ # keep those for which the sum equals the target ◴ # and deduplicate 
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 8 bytes

{5.ÆÙʒOQ 

Inputs in the order \$array,target\$. Outputs [] if there is no valid result.

Try it online or verify all test cases.

Explanation:

{ # Sort the first (implicit) input-list 5.Æ # Get all 5-element combinations of this list Ù # Uniquify this list of quintuplets ʒ # Filter it by: O # Where the sum of the quintuplet Q # Equals the second (implicit) input-integer # (after which the result is output implicitly) 
\$\endgroup\$
2
\$\begingroup\$

Japt, 12 bytes

Outputs an empty array if no solution is possible.

Íà5 â fÈx ¶V 

Try it

Íà5 â fÈx ¶V :Implicit input of array U & target integer V Í :Sort U à5 :Combinations of length 5 â :Deduplicate f :Filter by È :Passing through the following function x : Reduce by addition ¶V : Equal to V? 
\$\endgroup\$
2
  • \$\begingroup\$ Why doesn't Í pop up in the 'Search method' in the online compiler? I searched for sort and it didn't pop up, and even if I search directly for Í, only the lowercase versions pop up. 🤔 (Hence why I mentioned ñ as sort instead.) \$\endgroup\$ Commented Dec 11, 2024 at 10:05
  • \$\begingroup\$ @KevinCruijssen, Í is a (shortcut)[petershaggynoble.github.io/Japt-Interpreter/… for n2<space>. It's primary intent is for use on strings, where the n method converts to an integer and the 2 argument specifies from binary. The n method when used on an array, though, sorts the array and the 2 is ignored as the method doesn't expect an integer as an argument. \$\endgroup\$ Commented Dec 11, 2024 at 10:16
2
\$\begingroup\$

JavaScript (V8), 91 bytes

f=([c,...x],s,n=R=[])=>1/n[4]?s||R[n.sort()]||print(R[n]=n):1/c&&f(x,s,n)^f(x,s-c,[...n,c]) 

Try it online!

JavaScript (Node.js), 97 bytes

f=([c,...x],s,n=R=[])=>1/n[4]?s||R[n.sort()]?[]:[R[n]=n]:1/c?[...f(x,s,n),...f(x,s-c,[...n,c])]:x 

Try it online!

JavaScript (Node.js), 98 bytes

f=(x,s,i=R={},...n)=>1/n[4]?s||R[n.sort()]?[]:[R[n]=n]:x.flatMap((e,j)=>i<=j?[]:f(x,s-e,j,...n,e)) 

Try it online!

Dedup

\$\endgroup\$
1
  • \$\begingroup\$ f=([c,...x],s,n=R=[])=>1/n[4]?R[n.sort()]??=s||+print(n):1/c?f(x,s,n)^f(x,s-c,[...n,c]):x \$\endgroup\$ Commented Dec 11, 2024 at 9:52
2
\$\begingroup\$

Wolfram Language (Mathematica), 68 bytes 50 bytes 40 bytes 37 bytes

Union@Pick[a=#~Subsets~{5},Tr/@a,#2]& 

Try it online!


Note

Returning "all possible permutations of one single array" is permitted eg test case 7:

Array: [1,0,9,6,5,0] Target: 21 Output: [[1,0,9,6,5],[1,9,6,5,0]] 

Saved 31 bytes by

  1. Switching to Cases from Select allowed me to use a pure function

  2. Union instead of DeleteDuplicates

  3. Using Infix ~ on Subset

  4. Using Tr instead of Total (thanks att!)

  5. Not pre-sorting (Sort/@) input as permutations of output is permitted

  6. Using Pick instead of Cases (thanks again att!)

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Total -> Tr \$\endgroup\$ Commented Jan 6 at 19:14
  • 1
    \$\begingroup\$ I'd say returning all permutations is allowed, as long as it returns at least 1. \$\endgroup\$ Commented Jan 6 at 22:08
  • 1
    \$\begingroup\$ 37 bytes with Pick \$\endgroup\$ Commented Jan 8 at 9:05
  • \$\begingroup\$ Pick is such a clear use case here, can't believe I missed it! \$\endgroup\$ Commented Jan 9 at 3:14
1
\$\begingroup\$

JavaScript (V8), 91 bytes

f=([v,...a],n,o=q=[])=>o[4]?n||q[o.sort()]||print(q[o]=o):v+1&&f(a,n-v,[...o,[v]])|f(a,n,o) 

Try it online!

Commented

f = ( // f is a recursive function taking: [v, // v = next value from the input array ...a], // a[] = remaining values n, // n = target sum o = // o[] = current output array q = [] // q = object to keep track of output arrays ) => // o[4] ? // if o[4] is defined: n || // unless n is not 0 q[o.sort()] || // or q[o] is defined (with o[] sorted), print(q[o] = o) // print o[] and set q[o] : // else: v + 1 && // unless v is undefined, f( // do a 1st recursive call: a, // pass a[] n - v, // subtract v from n [...o, [v]] // append [v] to o[] ) | // end of recursive call f(a, n, o) // do a 2nd recursive call with everything unchanged 
\$\endgroup\$
1
\$\begingroup\$

R, 52 bytes

\(x,n)unique(t(combn(x,5,sort)[,combn(x,5,sum)==n])) 

Attempt This Online!

Returns quintuplets as rows of a matrix.

\$\endgroup\$
1
\$\begingroup\$

APL, 63 chars

{⍺{⍵/⍨(⍺∘=+/∧5∘=∘≢)¨⍵}{0=≢⍵:1⍴⊂⍬⋄⊃,/(⊃⍵){(⊂⍵),⊂⍵,1⍴⍺}¨(∇1↓⍵)}⍵} 

Takes the target on the left and the list of numbers on the right. Explanation, broken out slightly into a helper function:

combos←{0=≢⍵:1⍴⊂⍬⋄⊃,/(⊃⍵){(⊂⍵),⊂⍵,1⍴⍺}¨(∇1↓⍵)} ⍝ Recursively generate all combinations of the input array 0=≢⍵: ⍝ If the input is empty 1⍴⊂⍬ ⍝ return a one-element array containing an empty array (∇1↓⍵) ⍝ Otherwise recursively call with the tail of the list (⊃⍵){ }¨ ⍝ And apply to each result with the head of the list as the left input ⊂⍵,1⍴⍺ ⍝ Concat the right input with an array made from the left input (⊂⍵), ⍝ And concat with the input itself ⊃,/ ⍝ Join and disclose to not further nest the result {⍺{⍵/⍨(⍺∘=+/∧5∘=∘≢)¨⍵} combos ⍵} { ¨⍵} ⍝ Take all the possible combinations ⍵/⍨ ⍝ And replicate those that pass: ( ∧ ) ⍝ the AND of ⍺∘=+/ ⍝ the left input matches their sum 5∘=∘≢ ⍝ the right input has 5 elements 
\$\endgroup\$
1
\$\begingroup\$

Scala 3, 36 bytes

t=>_ combinations 5 filter(_.sum==t) 

Attempt This Online!

A function of type Int => Seq[Int] => Iterator[Seq[Int]].

\$\endgroup\$
1
\$\begingroup\$

Haskell + hgl, 21 bytes

nB sr<<ss5><fl<eq^.sm 

Attempt This Online!

Explanation

The order of operations is a bit strange here.

  • ss5 get all quintuples
  • fl filter those that ...
  • sm their sum ...
  • eq is equal to the input
  • nB sr remove duplicates after sorting.

Reflection

We have some pretty good builtins here. The only 3-byte builtin is ss5 which definitely should not be a 2-byte function. It seems like we use a lot of glue, but it's not an area I can see much improvement. I really have all the glue I want. There's no parens and we don't even use any 3-byte composes.

It seems long but I don't really know how it could be shorter.

The only possible improvement is to make nB sr a builtin. I don't really know if this would be useful in the long term.

\$\endgroup\$
1
\$\begingroup\$

Arturo, 51 bytes

$[a,t][a|sort|combine.by:5|select=>[t=∑&]|unique] 

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Jelly, 9 bytes

Ṣœc5S=¥ƇQ 

Try it online!

Loses to the Vyxal answer by 1 char as Jelly's combinations monad is 2 characters: œc.

Ṣœc5S=¥ƇQ Main, dyadic link. Arguments: list, n Ṣ Sort (to help with dedup) œc5 Generate all 5-permutations S=¥ Dyadic link: is the sum of the list = n? Ƈ Filter by Q Deduplicate 
\$\endgroup\$
1
\$\begingroup\$

Nekomata, 9 bytes

oS5Lũᵖ{∑= 

Attempt This Online!

oS5Lũᵖ{∑= o Sort the first input S Find a subset 5L Check that it has length 5 ũ Remove duplicate values of a non-deterministic object ᵖ{ Check that it satisfies the following condition: ∑ Its sum = Is equal to the second input 
\$\endgroup\$
1
\$\begingroup\$

Zsh, 99 bytes

Non-deterministic, but repeated calls to shuf is a good-enough solution for picking 5 numbers from a list.

t=$1;shift;${5?};{repeat $[2**#] S=(`shuf -n5<<<${(F)@}`)&&((${(j:+:)S}==t))&&echo ${(n)S}}|sort -u 

Try it online!, or try the 160-byte deterministic solution 175b 189b 192b

\$\endgroup\$
1
\$\begingroup\$

Husk, 8 bytes

ufo=⁰ΣṖ5 

Try it online!

Inputs target and array as separate arguments. Outputs [] if there is no valid solution.

Commented:

 Ṗ5 -- make a list of all possible quintuplets f -- filter the quintuplets... o=⁰Σ -- | that sum to the target u -- deduplicate 
\$\endgroup\$
1
\$\begingroup\$

Python 3, 755 674 576 573 376 88 85 77 71 bytes

-81 bytes thanks to @corvus_192
-98 bytes
-3 bytes
-197 bytes
-288 bytes thanks to @roblogic
-3 bytes
-8 bytes
-6 bytes

Changelog

Date Time Size Byte save User Credit (OG-csize)/OG -----------+-----------+-----------+------------+------------+-------------+ 2024-12-11 | 01:21:34Z | 755 bytes | -000 bytes | CrSb0001 | 00.00% | -----------+-----------+-----------+------------+------------+-------------+ 2024-12-13 | 15:32:42Z | 674 bytes | -081 bytes | corvus_192 | 10.73% | -----------+-----------+-----------+------------+------------+-------------+ 2025-01-06 | 21:34:44Z | 576 bytes | -098 bytes | CrSb0001 | 23.71% | -----------+-----------+-----------+------------+------------+-------------+ 2025-01-22 | 19:02:07Z | 573 bytes | -003 bytes | CrSb0001 | 24.11% | -----------+-----------+-----------+------------+------------+-------------+ 2025-03-19 | 23:33:17Z | 376 bytes | -197 bytes | CrSb0001 | 50.20% | -----------+-----------+-----------+------------+------------+-------------+ 2025-03-20 | 00:34:46Z | 088 bytes | -288 bytes | roblogic | 88.34% | | | | | CrSb0001 | | -----------+-----------+-----------+------------+------------+-------------+ 2025-03-20 | 00:49:56Z | 085 bytes | -003 bytes | CrSb0001 | 88.70% | -----------+-----------+-----------+------------+------------+-------------+ 2025-03-20 | 14:52:00Z | 077 bytes | -008 bytes | CrSb0001 | 89.80% | -----------+-----------+-----------+------------+------------+-------------+ 2025-03-21 | 16:07:30Z | 071 bytes | -006 bytes | CrSb0001 | 90.60% | -----------+-----------+-----------+------------+------------+-------------+ 

@corvus_192's comment from 2024-12-13
@roblogic's comment from 2025-02-06


from itertools import* lambda:{c for c in combinations(n,5)if sum(c)==t} 

(returns a list set of sorted lists tuples, or set() if there are none/array len is less than 5.)

Note that this is still a valid solution as 1) it's still a lambda function, just anonymous and 2) we can simply define n and t below before doing the unittests.


I've been trying to figure out how I can use itertools to help, but I'm admittedly unable to come up with anything. @roblogic, I am SO sorry for not taking the time to look into itertools.combinations, it ended up saving me a total of 667 670 684 bytes compared to my original solution!




Old 755:

def fiveSum (nums,target): nums.sort() s=[] for i in range(len(nums)-4): if i>0 and nums[i]==nums[i-1]: continue for j in range(i+1,len(nums)-3): for k in range(j+1,len(nums)-2): l,m=k+1,len(nums)-1 while l<m: a=nums[i]+nums[j]+nums[k]+nums[l]+nums[m] if a<target: l+=1 elif a>target: m-=1 else: s.append((nums[i],nums[j],nums[k],nums[l],nums[m])) l+=1 while nums[l]==nums[l-1] and l<m: l+=1 k=[] for b in list(set(s)): k.append(list(b)) return k 

Explanation:

def fiveSum (nums,target): nums.sort() # does NOT return all 4 solutions for the last case if removed, unsure why s=[] # ^ (only returns two/four arrays) for i in range(len(nums)-4): # i < j < k < l < m if i>0 and nums[i]==nums[i-1]: # later loops will cover all of the continue # other cases, so no need to recurse through them again for j in range(i+1,len(nums)-3): # for j in range for k in range(j+1,len(nums)-2): # for k in range l,m=k+1,len(nums)-1 # No more "_ in range" needed anymore while l<m: # i < j < k < l < m a=nums[i]+nums[j]+nums[k]+nums[l]+nums[m] # The sum if a<target: # check if nums[0]+nums[1]+...+nums[4] == target l+=1 # it probably doesn't, so increment l by 1 elif a>target: # if overshoot m-=1 # if it does, decrement m by 1 else: s.append((nums[i],nums[j],nums[k],nums[l],nums[m])) # append to list l+=1 while nums[l]==nums[l-1] and l<m: # More incrementation! (Yay?) l+=1 k=[] # The final list for b in list(set(s)): k.append(list(b)) return k # return List[List[str]] 
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Try to use one-letter variable names to save even more bytes \$\endgroup\$ Commented Dec 13, 2024 at 14:40
  • \$\begingroup\$ This hurts to read on a code golf site. See our tips for golfing in python. You're allowed to import libraries, in this case why not use itertools.comb \$\endgroup\$ Commented Feb 6 at 11:06
  • 1
    \$\begingroup\$ Hey @roblogic, sorry for not implementing your idea right away. I think you'll very much appreciate what I've managed to come up with. (directly below the changelog) \$\endgroup\$ Commented Mar 20 at 0:34
  • \$\begingroup\$ Nice work! 85 bytes is seriously good golfing \$\endgroup\$ Commented Mar 20 at 9:38
  • \$\begingroup\$ @roblogic Actually, since I made I/O flexible, I can save 3 bytes by removing the brackets and then not unpacking the set, since it still gives the unique combinations (given as tuples). Also, maybe I could remove the f= at the beginning since wouldn't it still be a valid lambda expression, so saving a total of 5 bytes? \$\endgroup\$ Commented Mar 20 at 13:24
0
\$\begingroup\$

Maple, 57 bytes

(n,t)->[{select(x->add(x)=t,combinat:-choose(n,5))[]}[]]; 

Explanation:

Input: n = nums (list), t = target.

combinat:-choose outputs combinations in lex order.

select filters for those that add to the target.

conversion from list to set {...[]} makes unique, then [...[]] converts back to a list.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.