awelgorithms

3Sum: the skills you need first

Updated

LeetCode · medium · two pointers. Sort, fix i, then two-sum the suffix. Skip duplicates at every pointer.

open on LeetCode

Skills this problem builds on

Stuck on 3Sum? It is usually one of these. Get each one solid and the solution stops being a trick.

  1. Fix one index then face the rest

    Three-sum fixes i, then runs opposite pointers on the suffix: L = i+1, R = n-1. The pair at L, R plus a[i] is the triple. Then i += 1 and repeat.

  2. Skip equal neighbors after a hit

    After you record a pair, advance L while a[L] equals the used left, and R while a[R] equals the used right. For a fixed i, skip equal i after that i is done.

  3. Generate unique triplets
check which ones you have 10 minutes, free, no account.

More two pointers problems