DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Linear foundations · Topic 2 of 18

Two Pointers

Two indexes walk the list together (often from both ends), so each step rules something out for good.

Watch in Lens

Spot it

Signals in the question

⌕The input is sorted, or sorting it wouldn't hurt.

⌕You're looking for a pair (or triple) that meets a target.

⌕You need to compare or swap from both ends (palindromes, reversing, containers).

The idea

O(n) time · O(1) space

Put one pointer at each end. If the pair is too small, only moving the left one up can help; if too big, only moving the right one down can. Every step drops one number for good, so it's one pass.

Template · Both ends

1def pair_sum(nums, target):2    l, r = 0, len(nums) - 13    while l < r:4        s = nums[l] + nums[r]5        if s == target:6            return [l, r]7        if s < target:8            l += 19        else:10            r -= 111    return []

The template, filled in for Two Sum II (sorted input). The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchTwo Pointers, explainedNeetCode · YouTube · free↗¶ReadTwo pointers techniqueGeeksforGeeks · free↗

Practice set

Loading your mission…

Common mistakes

1Using two pointers on unsorted data: the "too small, move left" logic only holds when sorted.

2while l <= r for pairs: the two pointers must point at different items.

3Moving both pointers after a miss, skipping possible answers.

Check yourself

Question 1 of 2

Sorted list, sum of the ends is too big. What do you do?