4Sum - Problem

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

0 <= a, b, c, d < n
a, b, c, and d are distinct
nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
💡 Note: Three unique quadruplets sum to 0: [-2,-1,1,2], [-2,0,0,2], and [-1,0,0,1]
Example 2 — No Solution
$ Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
💡 Note: Only one unique quadruplet: [2,2,2,2] with sum = 8
Example 3 — Empty Result
$ Input: nums = [1,2,3,4], target = 20
Output: []
💡 Note: No four numbers can sum to 20, maximum possible is 1+2+3+4=10

Constraints

  • 1 ≤ nums.length ≤ 200
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ target ≤ 109

Visualization

Tap to expand
4Sum Problem INPUT nums array: 1 0 -1 0 -2 2 0 1 2 3 4 5 target = 0 Sorted array: -2 -1 0 0 1 2 Find 4 numbers that sum to target ALGORITHM STEPS 1 Sort Array O(n log n) sorting 2 Fix First Two (i, j) Two nested loops 3 Two Pointers (L, R) Find remaining pair 4 Skip Duplicates Ensure unique quads Two Pointer Technique: i j L ... R Time: O(n^3) | Space: O(1) FINAL RESULT Unique Quadruplets Found: Quad 1: -2 -1 1 2 = 0 Quad 2: -2 0 0 2 = 0 Quad 3: -1 0 0 1 = 0 Output: [[-2,-1,1,2], [-2,0,0,2],[-1,0,0,1]] OK - 3 unique quadruplets Key Insight: Reduce to 2Sum: Fix two elements with nested loops (i, j), then use two-pointer technique on remaining elements to find pairs summing to (target - nums[i] - nums[j]). Skip duplicates at each level to ensure unique quadruplets. Sorting enables efficient duplicate detection and two-pointer approach. TutorialsPoint - 4Sum | Optimal Two-Pointer Solution
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
25.2K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen