You are given a list of whole numbers, nums, and a number target. Find every quadruplet: four numbers taken from four different positions whose sum is exactly target.
Two quadruplets that hold the same four values count as one, so the answer must not repeat a set of values. Return the quadruplets in any order.
Example 1
Input: nums = [2, 0, -1, 1, 1, -1], target = 1 Output: [[-1, -1, 1, 2], [-1, 0, 1, 1]] Why: two different sets of four values add up to 1
2 more examples and the constraints
Example 2
Input: nums = [5, 5, 5, 5, 5], target = 20 Output: [[5, 5, 5, 5]] Why: five ways to pick four 5s, but only one set of values
Example 3
Input: nums = [1, 2, 3], target = 6 Output: [] Why: there are not even four numbers to pick
Constraints
- 1 ≤ length of nums ≤ 200
- −1,000,000,000 ≤ each number ≤ 1,000,000,000
- −1,000,000,000 ≤ target ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute force with a setO(n⁴)
- Sort + two loops + two pointersO(n³)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200 numbers | Verdict |
|---|---|---|---|
| Brute force with a set | O(n⁴) | Mention it, then move on | |
| Sort + two loops + two pointers | O(n³) | Best; the expected answer |
n = how many numbers are in the list, r = how many quadruplets are returned.
Edge cases to test
- Fewer than four numbers. [1, 2, 3] has no quadruplet: return [].
- All the same value. [5, 5, 5, 5, 5] with target 20 gives one answer, not five.
- Overflow. Four copies of 1,000,000,000 with target −294,967,296 must return []: a 32-bit sum would wrap to exactly that.
- Negative target. [-5, -4, -3, -2, -1] with target −14 gives [-5, -4, -3, -2].
Common mistakes
- Adding four ints in a 32-bit int, which overflows for values near the limits.
- Skipping a repeated
jwithj > 0instead ofj > i + 1, which wrongly drops answers like [-1, -1, 1, 2]. - Forgetting to skip repeats at all, so the same quadruplet is listed twice.
How to talk through it
- 1Clarify. Can values repeat? Must the answer list distinct value sets? Can the sum overflow?
- 2Give the brute force. Four loops and a set; say it is O(n⁴), about 65 million sums at n = 200.
- 3Reduce to two-sum. Sort, fix two values with loops, and solve the rest with two pointers.
- 4Code the skips. Explain each skip: a repeated first value, a repeated second value, a repeated third after a hit.
- 5Test out loud. Run all-equal values, fewer than four numbers, and the overflow case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?