Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

All distinct quadruplets with a given sum

Medium · Target 20 minutes · Two pointers· Type asked at

You're given an integer array nums and a target. I'd like you to return every distinct quadruplet [a, b, c, d] whose sum is target, where the four values come from four different positions in the array. Each one should be written smallest first and you list them in ascending order as well (by the first value, and then the second if that's a tie, and so on). If two quadruplets have the same four values they only count once.

Examples

InputOutputWhy
nums = [1, 0, -1, 0, -2, 2], target = 0[-2,-1,1,2] [-2,0,0,2] [-1,0,0,1]The two 0's can both go in the same quadruplet because they sit at different positions.
nums = [2, 2, 2, 2, 2], target = 8[2,2,2,2]There are five ways to choose four of the 2's but they're all the same quadruplet.
nums = [1, 2, 3], target = 6(none)You can't make a quadruplet out of three values.

Constraints

  • 1 ≤ n ≤ 200
  • −10⁶ ≤ nums[i] ≤ 10⁶
  • −4 × 10⁶ ≤ target ≤ 4 × 10⁶

Hints

Hint 1

If you've done 3-sum with a sort and two pointers you've done most of this. What would you need to add on the outside to get to four values?

Hint 2

Sort it and fix two values with two nested loops over i < j, and then the last two come from a pair scan on everything to the right of j.

Hint 3

You'll get duplicates from three places: the same value fixed twice at i, the same value fixed twice at j, and the pointers landing on repeats after a hit. Skip all three the same way you did in 3-sum.

Where people lose marks

  • Skipping a repeated j even when j = i + 1, which I've seen quite a lot. You'll lose quadruplets like [2, 2, 2, 2] where the second value happens to be the same as the first one.
  • Moving lo and hi on by one step each after a hit, so that if the next value's the same you find the same quadruplet again and it shows up twice in the output.
  • Overflow in a language with fixed-width ints once the values get near 10⁹. They're capped at 10⁶ here so a 32-bit int's fine, but I'd probably still mention it in an interview.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.