DSA and coding Level 2 This level · 29 of 30
Medium dsa two-pointers

3Sum

The 30 second answer

I sort the array, then fix one number and run the opposite-ends two-pointer search for a pair that sums to its negation. I skip duplicate values at the fixed index and at both pointers so each triplet appears once. Sorting costs n log n, and the two-pointer pass is quadratic, which is the expected bound.

Could you say this in an interview?

Problem Given an integer array, return all unique triplets [a, b, c] such that the three values are at different indices and a + b + c = 0. The triplets may be returned in any order, but each unique combination of values should appear once. Original: LeetCode 15: 3Sum.

Understanding the prompt "Unique" refers to the values, not the indices: [-1,0,1] should appear once even if -1 occurs twice in positions that could form it more than one way, while [-1,-1,2] is a different triplet and must be kept when two -1 values exist.

Pattern recognition k-Sum: sort, fix the first k−2 values, and solve the rest with opposite-ends two pointers. For k = 3 the inner step is a Two Sum II.

Brute force Try every triple and store it in a set of sorted tuples: O(n³) time and extra hashing cost.

Optimal Sort. For each index i, skip it if it is the same value as i−1, then run two pointers on the suffix for a pair that sums to -nums[i]. When a pair hits the target, record it and skip duplicate values on both sides. A suffix that cannot reach zero (the smallest two already overshoot, or the largest two already fall short) can exit early, but the skip logic is the part interviewers watch for.

Alternatives For each i, solve Two Sum on the suffix with a hash set. That is also O(n²), but the set uses extra memory and makes de-duplication messier than the sorted two-pointer version.

Java solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        var ans = new ArrayList<List<Integer>>();
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int lo = i + 1, hi = nums.length - 1;
            while (lo < hi) {
                int sum = nums[i] + nums[lo] + nums[hi];
                if (sum == 0) {
                    ans.add(List.of(nums[i], nums[lo], nums[hi]));
                    lo++;
                    hi--;
                    while (lo < hi && nums[lo] == nums[lo - 1]) lo++;
                    while (lo < hi && nums[hi] == nums[hi + 1]) hi--;
                } else if (sum < 0) lo++;
                else hi--;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(threeSum(new int[] {-1, 0, 1, 2, -1, -4})); // [[-1, -1, 2], [-1, 0, 1]]
        System.out.println(threeSum(new int[] {0, 1, 1}));             // []
        System.out.println(threeSum(new int[] {0, 0, 0}));             // [[0, 0, 0]]
    }
}

Complexity O(n²) time after an O(n log n) sort. O(1) extra space besides the output, if you sort in place.

Edge cases

  • All zeros, which should return [[0,0,0]] once.
  • Fewer than three values, or no triplet that sums to zero, as in [0,1,1].
  • A mix of duplicates that still forms more than one distinct triplet, as in [-1,0,1,2,-1,-4].

Follow-ups

  • 3Sum closest, or 4Sum: the same pattern with one more loop.
  • This problem is regularly named in public Microsoft interview reports.

Tests [-1,0,1,2,-1,-4] returns [[-1,-1,2],[-1,0,1]]. [0,1,1] returns []. [0,0,0] returns [[0,0,0]].

How to say it in the interview "I sort, then fix one number and use two pointers on the rest to find a pair that sums to its negation, which is the same idea as Two Sum II. I skip duplicates at the fixed index and on both pointers so each triplet is unique. After the sort, that's O(n²)."

Sources (3)
  1. LeetCode 15: 3Sumleetcode.com
  2. Java SE 17 API: Arrays.sortdocs.oracle.com
  3. LeetCode Discuss: Microsoft SDE-2 recent questions 2025 (candidate reports, secondary)leetcode.com
Previous
Next