Practice Lab

3Sum

Problem

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:

Why The Brute Force TLEs

The direct approach checks every triple:

for i
  for j
    for k

That is O(n^3). It can pass many test cases, but it times out near the upper limits.

Using a Set<List<Integer>> also adds overhead:

The main issue is still O(n^3), but the object creation makes it slower.

Optimized Idea

Sort the array first.

Then fix one number nums[i] and solve the remaining two-number problem using two pointers:

If the sum is too small, move left. If the sum is too large, move right. If the sum matches, record the triplet and skip duplicates.

Complexity

ApproachTimeSpace
Brute force triplesO(n^3)O(number of answers)
Sort + two pointersO(n^2)O(1) extra, excluding output

Java Solution

import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);

        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            if (nums[i] > 0) {
                break;
            }

            int left = i + 1;
            int right = n - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];

                if (sum == 0) {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));

                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }

                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }

        return result;
    }
}

Duplicate Rules

Skip duplicate fixed values:

if (i > 0 && nums[i] == nums[i - 1]) continue;

After finding a valid triplet, skip duplicate left and right values before moving both pointers.

Key Pattern

When a problem asks for unique pairs or triplets and order does not matter:

  1. Sort first.
  2. Fix one value if needed.
  3. Use two pointers for the remaining pair.
  4. Skip duplicates at the same decision level.