Skip to the workspace
Pebellslearn by building
Two Pointers  ›  Lesson

Fix One, Squeeze Two: Triples That Cancel Out

3Sum 15 minTo find every distinct triple with a target sum, sort the list, fix each value in turn and run a two-pointer squeeze on the values to its right, skipping repeated values.

leetcode / Fix One, Squeeze Two: Triples That Cancel Out

Explore each scene at your own pace.

01 · The rule

The rule

Fix One, Squeeze Two: Triples That Cancel Out

An accountant has a list of adjustments, credits positive and debits negative, and wants every distinct set of three entries that cancel out to exactly zero. Trying every triple is about n³ work, which already crawls at a few thousand entries. Pairs had a fast trick; triples can reuse it.

The rule

Sort, fix each value, then squeeze the rest for what it needs.

Once one value is fixed, the other two must add up to minus that value, and "two values with a known total in a sorted list" is exactly the sorted squeeze. So: sort once, loop over each position as the fixed value, and run a squeeze on everything to its right.

def zero_triples(nums):
    nums = sorted(nums)
    found = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue                        # same fixed value, same triples
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                found.append((nums[i], nums[left], nums[right]))
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1               # skip repeats of the value just used
    return found

The cost is n squeezes of up to n steps each, about n², plus the sort. Sorting does a second job for free: equal values sit side by side, so skipping duplicates is just "is this the same as the one before?" That is how the answer lists each triple once without needing a set.

Could the inner pair use the complement lookup from the hashing section instead? It could, and the total would still be about n², but it needs a fresh set for every fixed value, and keeping out repeated triples becomes much fiddlier without sorted order. The squeeze is the cleaner answer.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.