awelgorithms

Two Sum II: the skills you need first

Updated

LeetCode · medium · two pointers. Sorted input: too small, advance left; too large, retreat right.

open on LeetCode

Skills this problem builds on

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

  1. Target-sum with opposite pointers

    On a sorted array, L = 0 and R = n-1. If a[L]+a[R] equals target, that is the pair. If the sum is too small, L += 1. If too large, R -= 1.

  2. Require sorted order before facing pointers

    Opposite-end sum motion is correct only on a sorted array. If a is unsorted, sort a copy first. Facing [4, 1, 9] as if it were sorted lies about which end is smaller.

  3. Move left when the pair sum is too small

    If a[L]+a[R] < target, every pair using this L and a smaller right is even smaller. L += 1. R stays.

check which ones you have 10 minutes, free, no account.

More two pointers problems