15. 3Sum
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Two Pointers
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven an integer array, find all unique triplets of elements that add up to zero and return them as a list of lists.
Approach
- Sort the array, then fix one element at a time with an outer loop and reduce the remaining problem to a classic two-pointer search on the sorted suffix.
- Skip duplicate values for the fixed element (and for both pointers after a match) to guarantee uniqueness without a hash set.
- An early-break when the fixed element exceeds zero is valid because all remaining elements are at least as large, so no zero-sum triple is possible.
- Overall cost is dominated by the O(n²) nested scan; sorting is just O(n log n).
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int n = static_cast<int>(nums.size());
if (n < 3) return result;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; ++i) {
// Skip duplicate starting elements
if (i > 0 && nums[i] == nums[i - 1]) continue;
// All further elements are >= nums[i] > 0, no zero sum possible
if (nums[i] > 0) break;
int lo = i + 1, hi = n - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
if (sum == 0) {
result.push_back({nums[i], nums[lo], nums[hi]});
// Advance past duplicates on both sides
while (lo < hi && nums[lo] == nums[lo + 1]) ++lo;
while (lo < hi && nums[hi] == nums[hi - 1]) --hi;
++lo;
--hi;
} else if (sum < 0) {
++lo; // Need a larger value
} else {
--hi; // Need a smaller value
}
}
}
return result;
}
};
Time O(n²) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int n=nums.size();
if(n<3)
return result;
sort(nums.begin(), nums.end());
for(int i=0; i<n; ++i){
// reduce to two-sum problem
if(i>0 && nums[i]==nums[i-1])
continue;
// early exit
if(nums[i]>0)
break;
int j=i+1;
int k=n-1;
while(j<k){
int curSum=nums[i]+nums[j]+nums[k];
if(curSum==0){
result.push_back({nums[i], nums[j], nums[k]});
++j;
while(j<k && nums[j-1]==nums[j])
++j;
--k;
while(k>j && nums[k+1]==nums[k])
--k;
}
else if(curSum<0)
++j;
else
--k;
}
}
return result;
}
};
// Time: O(N^2)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.