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, and k are all different indices
  • nums[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
3Sum: The Triangle Balance GameTriangle Scale-4Fixed1Left3RightCurrent sum: -4 + 1 + 3 = 0 โœ“Algorithm Steps:1. Sort blocks: [-4, -1, -1, 0, 1, 2, 3]2. Fix first block (-4), find pairs that sum to +43. Use two pointers: left starts after fixed, right at end4. Move pointers based on current sum vs targetโœ“ Found: [-4, 1, 3] sums to 0
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables (excluding output space)

n
2n
โœ“ Linear Space

Constraints

  • 3 โ‰ค nums.length โ‰ค 3000
  • -105 โ‰ค nums[i] โ‰ค 105
  • The solution set must not contain duplicate triplets
Asked in
Google 89 Amazon 76 Meta 54 Microsoft 43
891.0K Views
Very High Frequency
~25 min Avg. Time
28.5K 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