PrepStack · Markdown HTML

Opposite-direction two pointers

Pointers and sliding window · HTML

Formal shape

Maintain candidate pair (l,r), l<r. Compare f(a[l],a[r]) with the target and move one endpoint; every skipped endpoint is proven unable to form an unchecked valid or better pair.

Recognition signals

False friends

SignalWhy it is different
Unsorted pairing with original indexesHashing is often O(n) without sorting; opposite pointers need sorting and index preservation.
Contiguous subarray constraintIf frequencies or sums over the full interval matter, use a variable window rather than only endpoint values.

Core invariant

Every uneliminated pair uses endpoints inside [l,r]; a moved endpoint is proven unable to pair with any remaining opposite endpoint to satisfy the goal.

State, transition, and processing order

ItemDefinition
StateLeft pointer l, right pointer r, endpoint values, and an optional best-so-far result.
TransitionCompare the endpoint combination; record or return a hit, move l when too small, and r when too large, as justified by monotonicity.
Frontier / orderA staircase boundary in the two-dimensional pair matrix, compressed into two one-dimensional pointers.

Python skeleton

def pair_with_sum(sorted_values, target):
    left, right = 0, len(sorted_values) - 1
    while left < right:
        total = sorted_values[left] + sorted_values[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

Correctness sketch

  1. If the sum is too small, the smallest endpoint paired with anything no larger than right cannot do better, so left is safely excluded.
  2. If the sum is too large, the symmetric argument excludes right.
  3. Each move preserves every possible solution and strictly shrinks the interval; a hit is valid and exhaustion proves absence.

Complexity

TimeSpaceParameters
O(n), or O(n log n) when sorting is requiredO(1), excluding a sorted copy or index mapn is the item count; each pointer moves at most n times.

Edge cases

Error patterns

PatternWhy it fails / fix
No elimination proofMoving the pointer that merely feels right can skip a solution.
Using left<=rightThat can pair an element with itself; ordinary two-item problems use left<right.
Losing original indexesWhen output needs original positions, sort (value,index) records.

Selection and exclusion rules

RelationTemplateBoundary
symmetry basisCenter expansion / Manacher palindromeValidating one given interval

Original micro-example

PartDetail
ResultThe selected endpoint values are 1 and 9.
SetupSorted values [1,4,6,9,13], target sum 10.
Trace1+13 is too large, so decrease the right endpoint to 9; 1+9 matches.

Recall prompts

My notes