Data Structures & Algorithms / Module 5: Algorithm patterns

Topic 5.1

Two pointers

Two markers moving through one array, ruling out one possibility at every step.

8 min · intermediate

Watch: two markers move in from both ends. Each step one of them shifts, and one possibility is ruled out.

0123456134681114
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 4

The list is sorted. Find two numbers that add up to 14.

PointerBecause the list is sorted, every check tells you which way to move. One number is ruled out at every step.

Why you may throw a number away

The list is sorted. Start with the smallest (lo) and the largest (hi).

  • If the sum is too big, the number at hi can't be in the answer. Its smallest possible partner is the number at lo, and even that is too much. So move hi left.
  • If it is too small, the number at lo can't be in the answer, for the same reason. Move lo right.

Every check rules out one number, so there are at most n − 1 checks. Trying every pair takes up to n(n − 1)/2.

Code, for programmersA pair with a given sum
function pairWithSum(sorted, target) {
  let lo = 0, hi = sorted.length - 1;
  while (lo < hi) {
    const sum = sorted[lo] + sorted[hi];
    if (sum === target) return [lo, hi];
    if (sum > target) hi--;     // hi is too big for any partner left
    else lo++;                  // lo is too small for any partner left
  }
  return null;
}

Other shapes of the same pattern

  • Reversing an array in place: swap the left and right ends, then move inwards (Module 0).
  • Checking a palindrome: compare the first letter with the last, the second with the second-to-last.
  • Read and write pointers: one pointer reads every element, another writes the ones you keep. Used to remove duplicates from a sorted array without a new array.
  • Merging two sorted lists: one pointer in each list, as in merge sort.

Quiz

  1. In a sorted list, lo + hi is bigger than the target. What do you do?

  2. At most how many checks does two pointers need on n numbers?

  3. The list isn't sorted. The fastest way to find a pair with a given sum?

0 of 3 answered.