Problem Solving — CS & DS

Lecture 19 — Invariants and Two Pointers

Learning objectives

Case-based lecture: you attempt, we discuss, then we reveal.

Today

The plan

Key definitions

Key definitions

Explain each in one breath; the cases will do the heavy lifting.
Worked example

The Palindrome Walk: two pointers closing in

cs-073

Is 'Level' a palindrome? Compare characters from both ends, ignoring case.

word = "Level"
lo, hi = 0, len(word) - 1
ok = True
while lo < hi:
    if word[lo].lower() != word[hi].lower():
        ok = False
        break
    lo += 1
    hi -= 1
print(ok)

Expected: True ('Level' is a palindrome, case-insensitively)

Cost: O(n) time but only n/2 comparisons, O(1) extra space - the reverse-compare alternative also reads O(n) but copies the string.

Worked example

The Pair Sum Contract: two pointers on sorted data

cs-074

Sorted values 1, 3, 4, 6, 8. Find a pair summing to 10, or report none.

a = [1, 3, 4, 6, 8]
lo, hi = 0, len(a) - 1
found = None
while lo < hi:
    s = a[lo] + a[hi]
    if s == 10:
        found = (a[lo], a[hi])
        break
    if s < 10:
        lo += 1
    else:
        hi -= 1
print(found)

Expected: pair found: 4 + 6 = 10

Cost: O(n) after sorting - each round removes one element from consideration for good; the all-pairs alternative is O(n^2).

Worked example

Partition by Parity: evens left, odds right, one pass

cs-075

Rearrange 3, 1, 2, 4 so all even numbers precede all odd numbers. Order within each group does not matter.

a = [3, 1, 2, 4]
lo, hi = 0, len(a) - 1
while lo < hi:
    if a[lo] % 2 == 0:
        lo += 1
    else:
        a[lo], a[hi] = a[hi], a[lo]
        hi -= 1
print(a)

Expected: [4, 2, 1, 3] - all evens before all odds

Cost: O(n) time, O(1) space, single pass - each step settles one element permanently.

Case attempt · lecture 19
Case cs-073 · Beginner

The Palindrome Walk

Check a palindrome with two pointers from both ends. State the invariant ('everything outside the pointers is verified') and why it ends correctly.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-073 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-073 — not embedded in this deck.

Case attempt · lecture 19
Case cs-074 · Foundational

The Pair Sum Contract

In a sorted list, find two elements summing to a target. The classic two-pointer; focus on the movement rule as an invariant, not a memorised trick.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-074 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-074 — not embedded in this deck.

Case attempt · lecture 19
Case cs-075 · Intermediate

Partition by Parity

Rearrange a list so evens precede odds, in-place. Two pointers from both ends with a loop invariant stated before code. Termination argument required.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-075 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-075 — not embedded in this deck.

Case attempt · lecture 19
Case cs-076 · Advanced

The Slow-Fast Cycle

Detect a cycle in a sequence given only a 'next' function (Floyd's idea). The invariant is about distance; the aha is why they must meet. Proof-shaped thinking.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-076 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-076 — not embedded in this deck.

Check yourself

Common misconceptions

Summary

Summary & exit question

Exit question (choose one, 60 seconds)

  1. State cs-074's invariant in one sentence.
  2. Why do two pointers give linear cost?
  3. What ends the slow/fast walk's doubt?
Expected answers (instructor): the answer pair, if it exists, lies within the current window each pointer moves at most n times; total moves 2n the gap strictly shrinks — termination is provable
→ / space: next · ←: back · Home/End: jump · Ctrl+P → PDF