Algorithms in Motion Algorithms Intermediate

Two pointers: squeezing a sorted array

Chapter 3 — Pair offers on a sorted price list

Promotions team wants pairs of distinct products whose prices sum to a campaign target (think "buy two for €50"). The price list is sorted — so you can walk two indices from both ends instead of trying every pair. That is two pointers: same catalog as before, but the question is about pairs, not a single lookup.

Pair-sum problem

Given a sorted array a and a target t, decide whether there exist two distinct indices i < j such that a[i] + a[j] == t.

public static boolean hasPairSum(int[] a, int t) {
    int left = 0, right = a.length - 1;
    while (left < right) {
        int sum = a[left] + a[right];
        if (sum == t) return true;
        if (sum < t) left++;    // too small: need a bigger number, move left right
        else         right--;   // too big: need a smaller number, move right left
    }
    return false;
}

Variations that all reuse the same idea

  • Remove duplicates from a sorted array in-place (slow/fast pointers).
  • Three-sum: fix i, run two pointers on the remainder.
  • Container with most water: both pointers at the ends of a height array.
  • Check if a string is a palindrome, ignoring case and non-letters.

Interactive — squeeze the array

Use the two-pointer lab with your own numbers; watch how each move shrinks the plausible pair space without revisiting dead combinations.

Open the two-pointer lab — drag your own sorted array →

Takeaways

  • Sorted input is what lets a single sweep replace a nested scan.
  • Each pointer move rejects an entire family of pairs, not just one.
  • The technique generalizes to triples, containers, and palindromes.
  • In the catalog story, pairs are the natural next question after you can search single prices fast.

Enjoying This Lesson?

Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.

Support Awashyak