Tech Interview RoomStudy guides

Two Pointers

3Sum: find all unique triplets that sum to zero. Show brute force, HashSet and sort + two pointers.

Intermediate · 2 min read · Lesson 3 of 5 in Two Pointers

Problem

[-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]]. No duplicate triplets in the output.

Pattern

Sort + fix one element + two pointers on the rest. Sorting lets you move pointers by comparing the sum with the target and lets you skip duplicates easily.

Approach 1: Three nested loops + a Set to remove duplicates (feasible, O(n³))

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

class ThreeSumBrute {
    static List<List<Integer>> find(int[] nums) {
        int[] a = nums.clone();
        Arrays.sort(a);                                      // so each triplet has a canonical order
        Set<List<Integer>> result = new LinkedHashSet<>();
        for (int i = 0; i < a.length; i++)
            for (int j = i + 1; j < a.length; j++)
                for (int k = j + 1; k < a.length; k++)
                    if (a[i] + a[j] + a[k] == 0) result.add(List.of(a[i], a[j], a[k]));
        return new ArrayList<>(result);
    }
}

Approach 2: Fix one element, HashSet for the other two (O(n²) time, O(n) space)

Reduces the inner problem to Two Sum.

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class ThreeSumHashSet {
    static List<List<Integer>> find(int[] nums) {
        int[] a = nums.clone();
        Arrays.sort(a);
        Set<List<Integer>> result = new LinkedHashSet<>();
        for (int i = 0; i < a.length - 2; i++) {
            if (i > 0 && a[i] == a[i - 1]) continue;
            Set<Integer> seen = new HashSet<>();
            for (int j = i + 1; j < a.length; j++) {
                int need = -a[i] - a[j];
                if (seen.contains(need)) result.add(List.of(a[i], need, a[j]));
                seen.add(a[j]);
            }
        }
        return new ArrayList<>(result);
    }
}

Approach 3: Sort + two pointers (O(n²) time, O(1) extra) — optimal

For each i, move lo up when the sum is too small and hi down when too big; skip duplicate values to avoid repeated triplets without a Set. Stop early when a[i] > 0.

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

class ThreeSumTwoPointers {
    static List<List<Integer>> find(int[] nums) {
        int[] a = nums.clone();
        Arrays.sort(a);
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < a.length - 2 && a[i] <= 0; i++) {
            if (i > 0 && a[i] == a[i - 1]) continue;              // skip duplicate first element
            int lo = i + 1, hi = a.length - 1;
            while (lo < hi) {
                int sum = a[i] + a[lo] + a[hi];
                if (sum < 0) lo++;
                else if (sum > 0) hi--;
                else {
                    result.add(List.of(a[i], a[lo], a[hi]));
                    while (lo < hi && a[lo] == a[lo + 1]) lo++;   // skip duplicates
                    while (lo < hi && a[hi] == a[hi - 1]) hi--;
                    lo++;
                    hi--;
                }
            }
        }
        return result;
    }
}

class ThreeSumDemo {
    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4, -2, 3};
        System.out.println(ThreeSumBrute.find(nums));
        System.out.println(ThreeSumHashSet.find(nums));
        System.out.println(ThreeSumTwoPointers.find(nums));   // [[-4, 1, 3], [-2, -1, 3], [-2, 0, 2], [-1, -1, 2], [-1, 0, 1]]
    }
}

Feasible → optimal

O(n³) brute force → O(n²) with a HashSet (extra memory, Set needed for de-duplication) → O(n²) with sort and two pointers using O(1) extra space and natural duplicate skipping. O(n²) is optimal for 3Sum in general.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): Two Sum II on a sorted array.

Put lo at the start and hi at the end; if the sum is too small move lo right, too big move hi left. O(n) time, O(1) space, because sorted order tells you which pointer to move.

Related (same pattern): 3Sum Closest and 4Sum.

3Sum Closest: same loop, but track the sum with the smallest |sum - target|. 4Sum: fix two indices with two nested loops (skipping duplicates at both levels), then two pointers: O(n³). The general k-Sum recursion reduces to 2Sum at the bottom.

Related (same pattern): count triplets with sum smaller than a target.

After sorting, for each i with pointers lo, hi: if a[i] + a[lo] + a[hi] < target, then every index between lo and hi also works with lo, so add hi - lo and move lo; otherwise move hi. O(n²).