3Sum - Problem
Given an integer array nums, your task is to find all unique triplets in the array that sum to zero.
A triplet is a set of three numbers [nums[i], nums[j], nums[k]] where:
i,j, andkare all different indicesnums[i] + nums[j] + nums[k] = 0
Important: The solution must not contain duplicate triplets. For example, if you find [-1, 0, 1], you should not also include [0, -1, 1] or [1, -1, 0] as they represent the same triplet.
Example: Given nums = [-1, 0, 1, 2, -1, -4], the unique triplets that sum to zero are [[-1, -1, 2], [-1, 0, 1]].
Input & Output
example_1.py โ Basic case with multiple triplets
$
Input:
nums = [-1,0,1,2,-1,-4]
โบ
Output:
[[-1,-1,2],[-1,0,1]]
๐ก Note:
The two unique triplets that sum to zero are [-1,-1,2] and [-1,0,1]. Note that the order of triplets and elements within triplets may vary.
example_2.py โ No valid triplets
$
Input:
nums = [0,1,1]
โบ
Output:
[]
๐ก Note:
The only possible triplet is [0,1,1] which sums to 2, not 0. Therefore, no valid triplets exist.
example_3.py โ All zeros
$
Input:
nums = [0,0,0]
โบ
Output:
[[0,0,0]]
๐ก Note:
The only possible triplet [0,0,0] sums to 0, so it's a valid answer.
Visualization
Tap to expand
Understanding the Visualization
1
Organize Blocks
First, arrange all blocks in order from lightest to heaviest (sorting)
2
Fix One Block
Choose one block as the pivot point of your triangle
3
Balance the Scale
Use two helpers at opposite ends to find blocks that balance the pivot
4
Avoid Duplicates
Skip identical blocks to avoid counting the same balance multiple times
Key Takeaway
๐ฏ Key Insight: Sorting first enables the two-pointer technique, which efficiently finds pairs while naturally avoiding duplicates through systematic pointer movement.
Time & Space Complexity
Time Complexity
O(nยณ)
Three nested loops each running up to n times
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables (excluding output space)
โ Linear Space
Constraints
- 3 โค nums.length โค 3000
- -105 โค nums[i] โค 105
- The solution set must not contain duplicate triplets
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code