3Sum

Find every unique triplet in an array summing to zero. Sort then two-pointer scan per anchor.

Medium
Time O(n^2) Space O(1)
LeetCode
5 min read
two-pointers array sorting

Problem#

Given an integer array nums, return all unique triplets [a, b, c] such that a + b + c == 0. The result must not contain duplicate triplets.

Examples#

  • [-1, 0, 1, 2, -1, -4][[-1, -1, 2], [-1, 0, 1]]
  • [0, 1, 1][]
  • [0, 0, 0][[0, 0, 0]]

Constraints#

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

Hints#

Hint 1
Sort first — it converts “find pair summing to X” into a two-pointer linear scan.
Hint 2
Skip duplicates at every level (anchor, left, right) to dedupe without a hash set.

Approach#

Hash-set per anchor — O(n²) time, O(n) space, dedup pain via set-of-tuples.
Sort + two-pointer per anchor — O(n²) time, O(1) extra space, dedup is a one-line skip.

Solution#

3Sum
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
const int n = nums.size();
for (int i = 0; i < n - 2; ++i) {
if (nums[i] > 0) break; // remaining sums > 0
if (i > 0 && nums[i] == nums[i - 1]) continue; // dedupe anchor
int l = i + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum < 0) ++l;
else if (sum > 0) --r;
else {
ans.push_back({nums[i], nums[l], nums[r]});
while (l < r && nums[l] == nums[l + 1]) ++l;
while (l < r && nums[r] == nums[r - 1]) --r;
++l; --r;
}
}
}
return ans;
}
};

Editorial#

Sorting unlocks two-pointer convergence: with nums[i] fixed, you need a pair summing to -nums[i], and the sorted invariant says moving l right increases the sum, moving r left decreases it. The early nums[i] > 0 break is tight: if the smallest element of the triplet is positive, no zero-sum triplet exists. The three “skip duplicates” guards are independent — they handle the same value appearing as anchor, as left, and as right respectively.

Complexity#

  • Time: O(n²) — n anchors × linear two-pointer pass.
  • Space: O(1) ignoring output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.