Python 3D Academyবাংলা

Why two pointers never miss: each move rules out a row of pairs

🌍 In real life. Back at the bookshelf with the 500-taka voucher: the cheapest book costs 80 and the dearest 700. Together 780: too much. Now think about the 700-taka book. Its cheapest possible partner is the 80-taka book, and even that is too much. So the 700-taka book can't be in any answer: cross it off, with every pair it could make, in one go.

That single thought is the whole reason the two-pointer search is both fast and correct.

The idea in one sentence: at every step, the pair being checked is the best hope for one of its two numbers, so if it fails, that number can be crossed off with all of its pairs.

Its words:

  • pair grid: a table with one square for every pair (i, j) with i < j: n(n − 1)/2 squares
  • ruling out: proving a pair can't be the answer without checking it
  • invariant: something that stays true after every step; here, "if there is an answer, it lies between L and R"

Picture every pair as a grid. Row i, column j holds the pair (i, j), for i < j: that is n(n − 1)/2 squares. Brute force visits every square. Two pointers:

  1. check the pair (L, R)
  2. sum too big: R's smallest possible partner is nums[L], and that already fails, so the whole column R is ruled out; R moves left
  3. sum too small: L's biggest possible partner is nums[R], and that fails too, so the whole row L is ruled out; L moves right

Watch the grid beside the list. Each check fades a whole row or column, so 3 checks cover all 6 pairs:

Why it is correct (the invariant). Every pair with a number outside L..R has already been ruled out. It is true at the start (nothing is outside), and each move keeps it true, because the number that leaves the range was crossed off with all its pairs. So when L meets R, every pair has been ruled out, and "no pair" is the right answer; and if a pair exists, the search must land on it before it could be ruled out.

What it costs, worked out. L and R start n − 1 apart, and each check (that doesn't find the pair) moves one of them a step closer, so there are at most n − 1 checks:

  • n = 4: at most 3 checks instead of 6 pairs
  • n = 100: at most 99 instead of 4,950
  • n = 1,000,000: at most 999,999 instead of about 500 billion

Here is a longer search that finds its pair:

def pair_checks(nums, target):
    l, r, checks = 0, len(nums) - 1, 0
    while l < r:
        checks += 1
        s = nums[l] + nums[r]
        if s == target:
            break
        if s < target:
            l += 1
        else:
            r -= 1
    return checks

nums = list(range(0, 2000, 2))       # 1,000 even numbers
print(pair_checks(nums, 1))           # no pair: odd target
print(len(nums) * (len(nums) - 1) // 2, "pairs in all")

Mistakes and edge cases. Moving the wrong pointer breaks the invariant: if the sum is too big and you move L, you cross off a number that might still have worked with a smaller partner. And the argument needs a sorted list; on an unsorted one, "its smallest possible partner is nums[L]" is simply false.

Quiz

  1. How many pairs (i, j) with i < j does a list of 6 numbers have? What does this print?

    n = 6
    print(n * (n - 1) // 2)
  2. nums = [1, 4, 6, 9], target 8: the first check is 1 + 9 = 10. Which pairs does moving R rule out?

    • Every pair with 9: 9 is too big even with the smallest number, 1
    • Every pair with 1
    • Only the pair (1, 9)
  3. What stays true after every move (the invariant)?

    • Every pair using a number outside L..R has been ruled out
    • nums[L] + nums[R] is always the target
    • L and R are always next to each other
  4. What does this print?

    nums = [1, 2, 3, 4, 5]
    l, r, checks = 0, 4, 0
    while l < r:
        checks += 1
        if nums[l] + nums[r] < 100:
            l += 1
        else:
            r -= 1
    print(checks)
  5. This misses pairs. Which line moves the wrong pointer?

    def pair_sum(nums, target):
        l, r = 0, len(nums) - 1
        while l < r:
            s = nums[l] + nums[r]
            if s == target:
                return l, r
            if s > target:
                l += 1
            else:
                r -= 1
        return None

Coding tasks

  1. Write pair_checks(nums, target): run the two-pointer pair search on the sorted list nums and give back how many sums it worked out (stop counting when it finds the pair).

  2. Write closest_sum(nums, target) for a sorted list of at least 2 numbers, in O(n) with two pointers: the sum of two numbers (different positions) closest to target. If two sums are equally close, give the smaller.