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: nums[0]+nums[1]+nums[5] = -1+0+2 = 1 ≠ 0, but nums[0]+nums[4]+nums[5] = -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: Find All Triplets That Sum to ZeroInput: [-1, 0, 1, 2, -1, -4]-1012-1-4Find all combinations where a + b + c = 0-1 + 1 + (-1) = -1 ≠ 0-1 + 0 + 1 = 0 ✓[-1, 0, 1][-1, -1, 2]Output: [[-1, -1, 2], [-1, 0, 1]]All unique triplets that sum to zero
Understanding the Visualization
1
Input
Array with positive and negative integers
2
Process
Find all unique triplets [a,b,c] where a+b+c=0
3
Output
List of all valid triplets
Key Takeaway
🎯 Key Insight: Sort first to enable two-pointer technique and handle duplicates efficiently
Asked in
Facebook 89 Amazon 67 Microsoft 45 Google 38
534.2K 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