Skip to lesson

Three sum and k-sum

Finding all unique triplets [nums[i], nums[j], nums[k]] that sum to 0 (3Sum) takes O(n³) time with three nested loops and requires a HashSet to filter out duplicate triplets. Sorting the array first lets you fix nums[i] and solve the remaining two numbers with converging two pointers in O(n²) total time and O(1) auxiliary working space.

Sort, then fix one number

3Sum finds the triplets whose sum is 0 by sorting the array, fixing one number and running a two-pointer pair search for the other two. First call Arrays.sort(nums) (O(n log n) time). Now loop an outer index i from 0 to n - 3.

Java
int[] nums = {-1, 0, 1, 2, -1, -4};Arrays.sort(nums);                          // [-4, -1, -1, 0, 1, 2]for (int i = 0; i < nums.length - 2; i++) {    if (nums[i] > 0) break;                 // everything after is > 0 too    int left = i + 1, right = nums.length - 1;    // Sorted Pair Sum on nums[left .. right] with target -nums[i]}

Once nums[i] is fixed as the smallest element of the triplet, finding nums[left] and nums[right] in the subarray i + 1 .. n - 1 such that nums[i] + nums[left] + nums[right] == 0 is just Sorted Pair Sum with target -nums[i]!

Because the array is sorted, you also get a free early-stop pruning check: if nums[i] > 0, then nums[left] and nums[right] (which lie to the right of i) are also > 0, so their sum can never equal 0. You can break out of the outer loop immediately!

  1. Sort the array with Arrays.sort(nums).
  2. Loop i from 0 to nums.length - 3 (and break early if nums[i] > 0).
  3. Set left = i + 1 and right = nums.length - 1.
  4. Run converging two pointers for sum = nums[i] + nums[left] + nums[right].

Skipping duplicates without missing valid triplets

The most common 3Sum bug is skipping duplicates in the wrong direction. For example, on [-1, -1, 2], the valid triplet uses two copies of -1 (i = 0 and left = 1).

Example 1 · Brute force: try every triple (O(n³) time, O(n) space)

ThreeSumBrute.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedHashSet;import java.util.List;import java.util.Set;
public class ThreeSumBrute {    public static List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        Set<List<Integer>> found = new LinkedHashSet<>();        int n = nums.length;        for (int i = 0; i < n; i++) {            for (int j = i + 1; j < n; j++) {                for (int k = j + 1; k < n; k++) {                    if (nums[i] + nums[j] + nums[k] == 0) {                        found.add(Arrays.asList(nums[i], nums[j], nums[k]));                    }                }            }        }        return new ArrayList<>(found);    }
    public static void main(String[] args) {        System.out.println("[-1,0,1,2,-1,-4]: " + threeSum(new int[]{-1, 0, 1, 2, -1, -4}));        System.out.println("[0,0,0,0]:        " + threeSum(new int[]{0, 0, 0, 0}));    }}
Output
[-1,0,1,2,-1,-4]: [[-1, -1, 2], [-1, 0, 1]]
[0,0,0,0]:        [[0, 0, 0]]

What this code does

  • Three loops test every triple, about n³ / 6 additions. A set removes repeated triplets, which is why the array is sorted first.
  • Once nums[i] and nums[j] are fixed, the third loop only looks for one value, -(nums[i] + nums[j]). Looking for one value is what a hash set does in O(1).

Example 2 · Better: fix one number, use a HashSet for the pair (O(n²) time, O(n) space)

ThreeSumHashSet.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.List;import java.util.Set;
public class ThreeSumHashSet {    public static List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        Set<List<Integer>> found = new LinkedHashSet<>();        int n = nums.length;        for (int i = 0; i < n - 2; i++) {            Set<Integer> seen = new HashSet<>();            for (int j = i + 1; j < n; j++) {                int need = -nums[i] - nums[j];                if (seen.contains(need)) {                    found.add(Arrays.asList(nums[i], need, nums[j]));                }                seen.add(nums[j]);            }        }        return new ArrayList<>(found);    }
    public static void main(String[] args) {        System.out.println("[-1,0,1,2,-1,-4]: " + threeSum(new int[]{-1, 0, 1, 2, -1, -4}));        System.out.println("[0,0,0,0]:        " + threeSum(new int[]{0, 0, 0, 0}));    }}
Output
[-1,0,1,2,-1,-4]: [[-1, 0, 1], [-1, -1, 2]]
[0,0,0,0]:        [[0, 0, 0]]

What this code does

  • The third loop becomes one seen.contains(need) lookup, so the work drops from n³ to about n² steps. The same triplets are found, in a different order.
  • It still needs O(n) extra memory for the sets, and the result set is needed to drop repeats. Sorting lets the two-pointer version do both jobs with no extra memory.

Example 3 · Optimal: sort, fix one number, two pointers (O(n²) time, O(1) extra space)

ThreeSumDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class ThreeSumDemo {    public static List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        List<List<Integer>> res = new ArrayList<>();        int n = nums.length;
        for (int i = 0; i < n - 2; i++) {            if (nums[i] > 0) break; // Smallest number > 0 cannot sum to 0            if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicate first element
            int left = i + 1, right = n - 1;            while (left < right) {                int sum = nums[i] + nums[left] + nums[right];                if (sum == 0) {                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));                    left++;                    right--;                    while (left < right && nums[left] == nums[left - 1]) left++;                    while (left < right && nums[right] == nums[right + 1]) right--;                } else if (sum < 0) {                    left++;                } else {                    right--;                }            }        }        return res;    }
    public static void main(String[] args) {        System.out.println("[-1,0,1,2,-1,-4]: " + threeSum(new int[]{-1, 0, 1, 2, -1, -4}));        System.out.println("[0,0,0,0]:        " + threeSum(new int[]{0, 0, 0, 0}));    }}
Output
[-1,0,1,2,-1,-4]: [[-1, -1, 2], [-1, 0, 1]]
[0,0,0,0]:        [[0, 0, 0]]

What this code does

  • Sorting [-1, 0, 1, 2, -1, -4] produces [-4, -1, -1, 0, 1, 2]. At i = 1 (nums[1] = -1), two pointers on [-1, 0, 1, 2] finds [-1, -1, 2] and [-1, 0, 1].
  • At i = 2 (nums[2] = -1), nums[2] == nums[1] triggers continue, avoiding duplicate triplets.
  • Why it is faster than brute force: the sorted order lets two pointers find the pair for each nums[i] in one O(n) sweep. Against the hash version, it needs no extra sets, and skipping equal neighbours removes repeats.
  • Never skip nums[i] == nums[i + 1] in the outer loop; always skip i > 0 && nums[i] == nums[i - 1].
  • Inside sum == 0: record the triplet first, advance both pointers once, and then skip nums[left] == nums[left - 1] and nums[right] == nums[right + 1].
  • No HashSet<List<Integer>> is needed!

If you write if (nums[i] == nums[i + 1]) continue; in the outer loop, you skip i = 0 and never allow nums[i] and nums[left] to share the value -1! Instead, always compare nums[i] with the previous index (i - 1), which has already been fully explored:

  • Outer loop: if (i > 0 && nums[i] == nums[i - 1]) continue;
  • Inner loop (after recording a match): increment left++ and decrement right--, then skip duplicates with while (left < right && nums[left] == nums[left - 1]) left++; and while (left < right && nums[right] == nums[right + 1]) right--;.

Find the bug

Find the 3Sum bug

Tap the line that is wrong.

The array is sorted. Which line breaks 3Sum on [-1, -1, 2]?

Round 1 of 3

Three sum closest and the k-sum idea

In 3Sum Closest, you want the triplet sum that minimizes Math.abs(sum - target).

Example 4 · 3Sum Closest in O(n^2) time

ThreeSumClosestDemo.javaJava
import java.util.Arrays;
public class ThreeSumClosestDemo {    public static int threeSumClosest(int[] nums, int target) {        Arrays.sort(nums);        int n = nums.length;        int closest = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < n - 2; i++) {            int left = i + 1, right = n - 1;            while (left < right) {                int sum = nums[i] + nums[left] + nums[right];                if (Math.abs(sum - target) < Math.abs(closest - target)) {                    closest = sum;                }                if (sum == target) {                    return target;                } else if (sum < target) {                    left++;                } else {                    right--;                }            }        }        return closest;    }
    public static void main(String[] args) {        System.out.println("Closest to 1 in [-1,2,1,-4]: " + threeSumClosest(new int[]{-1, 2, 1, -4}, 1));        System.out.println("Closest to 1 in [0,0,0]:     " + threeSumClosest(new int[]{0, 0, 0}, 1));    }}
Output
Closest to 1 in [-1,2,1,-4]: 2
Closest to 1 in [0,0,0]:     0

What this code does

  • In [-1, 2, 1, -4] with target = 1, the triplet (-1 + 2 + 1) = 2 has distance |2 - 1| = 1, which is the closest possible.
  • If sum == target, distance is 0, so we can return target immediately.

Example 5 · 4Sum in O(n^3) time with overflow-safe long arithmetic

FourSumDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class FourSumDemo {    public static List<List<Integer>> fourSum(int[] nums, int target) {        Arrays.sort(nums);        List<List<Integer>> res = new ArrayList<>();        int n = nums.length;
        for (int i = 0; i < n - 3; i++) {            if (i > 0 && nums[i] == nums[i - 1]) continue;            for (int j = i + 1; j < n - 2; j++) {                if (j > i + 1 && nums[j] == nums[j - 1]) continue;                int left = j + 1, right = n - 1;                while (left < right) {                    long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];                    if (sum == target) {                        res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));                        left++;                        right--;                        while (left < right && nums[left] == nums[left - 1]) left++;                        while (left < right && nums[right] == nums[right + 1]) right--;                    } else if (sum < target) {                        left++;                    } else {                        right--;                    }                }            }        }        return res;    }
    public static void main(String[] args) {        System.out.println("4Sum target 0: " + fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0));        System.out.println("4Sum [2,2,2,2,2] target 8: " + fourSum(new int[]{2, 2, 2, 2, 2}, 8));    }}
Output
4Sum target 0: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
4Sum [2,2,2,2,2] target 8: [[2, 2, 2, 2]]

What this code does

  • Notice the inner duplicate check if (j > i + 1 && nums[j] == nums[j - 1]) continue;: j is allowed to equal nums[i] on its very first step j == i + 1, and only skips duplicates for j > i + 1.
  • Using long sum prevents 32-bit overflow when four elements near 10⁹ are added.

Use the exact same Arrays.sort(nums), outer i loop, and inner left/right pointers: before moving left++ (when sum < target) or right-- (when sum > target), update closestSum whenever Math.abs(sum - target) < Math.abs(closestSum - target).

Extending to 4Sum and general k-Sum: Each additional number adds one outer loop (or one recursive level) that fixes an element, skips duplicates against the previous index (j > i + 1 && nums[j] == nums[j - 1]), and reduces k by 1 until k == 2, where the base case runs converging two pointers in O(n) time:

  • 2Sum (sorted): O(n)
  • 3Sum: O(n²)
  • 4Sum: O(n³)
  • k-Sum: O(n^(k - 1))
In 4Sum, four numbers up to 10⁹ can sum to 4 × 10⁹, which overflows 32-bit int! Always cast to long when computing sums of 3 or 4 large integers.

Next step

Check your understanding

10 quick questions