Mark As Completed Discussion

Good morning! Here's our prompt for today.

The Four Musketeers: Finding Quadruplets in an Array

Let's say you have a treasure chest, represented as an array of integers called nums. Your mission, should you choose to accept it, is to find four unique keys (numbers) from this treasure chest that unlock a magical target value when combined.

In other words, you have to find all unique sets of four integers [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 < a, b, c, d < length of array
  • a, b, c, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] = target

You can present these sets in any order you like!

Examples to Illuminate the Path

Example 1:

Input: Your treasure chest is [1,0,-1,0,-2,2] and the magical target is 0.
Output: The unique sets of keys that unlock the magical target are [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]].

Example 2:

Input: Your treasure chest is [2,2,2,2,2] and the magical target is 8.
Output: The only set of keys that unlock the magical target is [[2,2,2,2]].

Magical Constraints:

  • The treasure chest will have between 1 and 200 keys.
  • The value of each key and the magical target will range from -10^9 to 10^9.
Four Sum (4Sum)

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's how we would solve this problem...

How do I use this guide?

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.