Two pointers · Medium
3Sum: the idea to remember.
Return every distinct value triplet whose sum is zero.
The core insight
Sort, fix one value, and run a two pointer search on the suffix. Skip duplicate fixed values and duplicate pairs.
Why it works
For each fixed value, sorted order lets pointer movements exhaust all feasible complementary pairs.
The mistake to avoid
Skip duplicates after recording a valid triplet; do not accidentally skip distinct answers.
Time: O(n²)Space: O(log n) sorting stack, excluding output
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> out = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = nums.length - 1;
while (l < r) {
long sum = (long) nums[i] + nums[l] + nums[r];
if (sum < 0) l++;
else if (sum > 0) r--;
else {
out.add(Arrays.asList(nums[i], nums[l], nums[r]));
l++; r--;
while (l < r && nums[l] == nums[l - 1]) l++;
while (l < r && nums[r] == nums[r + 1]) r--;
}
}
}
return out;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.