Scanning from the Front or Back

Traversal direction determines which qualifying item a short-circuit search encounters first.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Specify a positional goal
  2. Keep original positions
  3. Check what happens when pointers meet
  4. Prove each alternative still reduces the remaining region

Specify a positional goal

In change records labeled open, closed, open, a front-to-back search for open finds position zero. A reverse search finds position two. For a sequence in chronological order, the latter can represent the most recent match. Define first-match behavior relative to traversal order.

Keep original positions

If you reverse a sequence and enumerate it, the resulting offset is measured from the reversed front. An original index can be computed as \(n-1-i\) for a full reversal. Zero-based indexing explains both endpoint conversions.[1]

Check what happens when pointers meet

For an input such as [r, a, d, a, r], compare indices zero and four, then indices one and three. At index two both pointers identify the same position, so no pair remains. A mismatch on the first comparison proves that [r, a, d, a, t] fails immediately under exact symbol comparison. If the comparison ignores punctuation or case, specify the normalization first and test characters that can expand to more than one code point. The range boundary convention can represent untouched positions as a slice, so you can check whether the loop skipped a needed comparison.

Prove each alternative still reduces the remaining region

Some two-pointer loops advance both pointers on a match and only one when conditions do not match. State which remaining candidates can be ruled out before moving either pointer. In a sorted pair-sum search, a current sum below the target lets you discard the smallest remaining value, because pairing it with any smaller right-side value would only reduce the sum. That reasoning requires sorted input. Test an odd and an even length, repeated values, and a no-solution case. An invariant for progress conditions is that each iteration reduces the interval's length by at least one.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩