DSA Visualizer · 25 visualizations3Sum
3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.
Sort first: [-4, -1, -1, 0, 1, 2]. Sorting lets us skip duplicates and use two pointers.
Problem
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.
Examples
Constraints
- 3 ≤ nums.length ≤ 3000
- -10⁵ ≤ nums[i] ≤ 10⁵
Intuition
Sort the array first. Then fix the smallest number of each triplet at index i and use two pointers — one just after i, one at the end — to find pairs that make the total 0, moving inward based on whether the sum is too small or too big. Sorting also makes duplicate triplets trivial to skip: just skip over repeated values at i, l and r.
Brute force → Optimal
Three nested loops over every (i, j, k) triplet, checking the sum and de-duplicating with a set.
Sort once (O(n log n)), then for each i run a two-pointer scan over the rest of the array (O(n)) — O(n²) overall, with no extra set needed since sorting makes duplicates adjacent.
Complexity
Edge cases
- Fewer than 3 numbers: no triplet is possible, return an empty list.
- All zeros, e.g. [0,0,0,0]: only one triplet [0,0,0] should appear, not one per combination — this is exactly what the duplicate-skipping handles.
Common mistakes
- Forgetting to skip duplicate values at i, which produces the same triplet more than once.
- Forgetting to skip duplicates at l and r *after* finding a match, which also produces repeated triplets.