3Sum - Problem

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
💡 Note: Two valid triplets that sum to zero: nums[0]+nums[4]+nums[3] = (-1)+(-1)+2 = 0 and nums[0]+nums[1]+nums[2] = (-1)+0+1 = 0
Example 2 — No Solution
$ Input: nums = [0,1,1]
Output: []
💡 Note: The only possible triplet is [0,1,1] but 0+1+1 = 2 ≠ 0, so no valid triplets exist
Example 3 — All Zeros
$ Input: nums = [0,0,0]
Output: [[0,0,0]]
💡 Note: The only triplet [0,0,0] sums to 0, which is valid

Constraints

  • 3 ≤ nums.length ≤ 3000
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
3Sum Problem - Optimal Solution INPUT Integer Array nums[] -1 i=0 0 i=1 1 i=2 2 i=3 -1 i=4 -4 i=5 Goal Find all unique triplets where nums[i]+nums[j]+nums[k]=0 Constraints: i != j != k No duplicate triplets Target sum = 0 ALGORITHM STEPS 1 Sort Array [-4,-1,-1,0,1,2] -4 -1 -1 0 1 2 2 Fix First Element Loop i from 0 to n-3 Skip duplicates for i 3 Two Pointers left = i+1, right = n-1 Find pairs that sum to -nums[i] -1 i -1 L 0 1 2 R 4 Adjust Pointers sum < 0: move L right sum > 0: move R left sum = 0: record, move both FINAL RESULT Found Triplets: [-1, -1, 2] -1 + (-1) + 2 = 0 [OK] [-1, 0, 1] -1 + 0 + 1 = 0 [OK] Output: [[-1,-1,2], [-1,0,1]] Complexity: Time: O(n^2) Space: O(1) or O(n) for sort Key Insight: Sorting enables the two-pointer technique. After fixing one element, use two pointers from both ends to find pairs summing to the negative of the fixed element. Skip duplicates to avoid repeated triplets. TutorialsPoint - 3Sum | Two Pointer Approach
Asked in
Facebook 89 Amazon 67 Microsoft 45 Google 38
534.6K Views
High Frequency
~25 min Avg. Time
18.4K 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