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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code