7 routes42 sections324 units

Unit 1.7 · about 5 h

94 / 324

Two pointers and sliding windows

Two pointers and windows replace nested loops with single passes wherever order or monotonicity lets one pointer's move settle another's. Recognizing the precondition is the skill.

  • derive
  • implement

You can now

  • State the ordering or monotonicity precondition before moving a pointer.
  • Implement opposite-ends, same-direction, fixed and variable windows with shrink triggers.
  • Construct the negative-numbers counterexample that breaks shrinking windows.

Covers

  • Two-pointer invariants and ordering assumptions
  • Fixed and variable windows and monotonicity

Study, in this order

4 steps

  1. Two pointers: opposite ends
    DSA Handbook - Foundations and linear patterns

    Why the proof actually works - the shorter-wall case analysis; The four primitives; Worked example LC 11 on [1, 8, 6, 2, 5, 4, 8, 3, 7]; Worked example LC 15 with the three duplicate-skips; What it actually costs

  2. Two pointers: same direction
    DSA Handbook - Foundations and linear patterns

    The four primitives (seed, scan, keep, commit); Worked example LC 26 on [1, 1, 2, 2, 3]; When the pattern bends (tail-fill LC 283, three-way partition LC 75, backward merge LC 88)

  3. Sliding window: fixed size
    DSA Handbook - Foundations and linear patterns

    The pattern (build-first-window then slide); The four primitives; Worked example LC 643 on [2, 1, 5, 1, 3, 2, 1, 4] with k = 3; Frequency-map slide with the matched counter (LC 567)

  4. Sliding window: variable size
    DSA Handbook - Foundations and linear patterns

    The pattern (expand right, shrink while broken); The four primitives plus the shrink trigger; Worked example LC 3 on pwwkew; Last-index jump; have == required for LC 76

Focus on

  • Opposite ends needs sortedness or an equivalent extremum argument; the shorter-wall move is proved by case analysis.
  • Variable windows need a monotone shrink trigger: all-nonnegative numbers for sums, distinctness for longest-substring.
  • Last-index jumps and matched counters keep \(O(1)\) per step; rescanning the window on each slide is the \(O(nk)\) trap.
  • Negatives break shrinking: the fix is prefix sums, next unit.

Reproduce closed-book

From a blank file, implement longest-substring with the last-seen jump and differential-test it against the \(O(n^2)\) brute force on alphabet abc up to length 12 (derandomize, max_examples=300) in Python 3.13: expect 1 passed. Then exhibit [1, -1, 1, 1] seeking the shortest subarray with sum at least 2: the shrink loop reports length 4 and misses the tail [1, 1] of length 2.

Traps

  • Forgetting to sort for opposite-ends moves, or sorting when the original indices are the answer.
  • Half-open confusion: an inclusive \([l, r]\) window changes the shrink condition and the length formula versus \([l, r)\).
  • Counters with stale zero entries: membership tests see dead keys unless counts are deleted or a have-counter is maintained.

Practice

LeetCode 167: Two Sum II - Input Array Is Sorted

Implement the opposite-ends move with the sortedness precondition stated in a comment. Judge with the Examples [2, 7, 11, 15] target 9 and [2, 3, 4] target 6.

After submitting, compare against the handbook two-pointers-opposite section The four primitives.

LeetCode 3: Longest Substring Without Repeating Characters

Attempt cold with hidden tags. Implement the variable window with last-seen jumps. Judge with the Examples abcabcbb, bbbbb and pwwkew.

After submitting, read the AlgoMaster Longest Substring write-up (https://algomaster.io/learn/dsa/longest-substring-without-repeating-characters) and the handbook variable-window worked example on pwwkew.

Self-test

  1. Prove the Container move: why advance the shorter wall?

  2. Why does the Two Sum II move rule fail on unsorted input?

  3. Trace the negatives counterexample [1, -1, 1, 1] with target sum at least 2.

  4. Why do the three 3Sum duplicate skips matter?

Completion criterion

Stop when

Both are accepted cold with the invariant stated first, and your negatives trace shows exactly which shrink step discards the optimum.

Mark passed, then open 1.8 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • DSA Handbook - Foundations and linear patterns
    Handbook Academyprimarycourse
    Study Part 0, Part 1, Part 3 and Part 4 in order, plus the Part 5 Linked-list fundamentals chapter. Use the routing-rule pages for arrays versus lists, map choice, stack versus queue, two pointers, sliding windows and prefix methods before seeing solved code.

Also in this section

  • AlgoMaster DSA - linear structures slice
    AlgoMasterrequiredpractice
    Attempt Design HashMap, Longest Substring Without Repeating Characters and Sliding Window Maximum cold. Hide tags, state the invariant first, and add randomized operation histories to Design HashMap.
  • MIT 6.042J - asymptotics and invariants
    MIT OpenCourseWaresupporttheory
    Use the asymptotics, state-machine invariants and proof-method readings when a cost or correctness argument is weak. Solve only the matching problems.
  • Algorithms lecture notes - amortized analysis and hashing
    Jeff Ericksonsupporttheory
    Use note 9 Amortized Analysis for the summation, taxation, charging and potential-function proofs, and note 5 Hashing for chaining, universal hashing and open-addressing analysis, when the handbook treatment is too brief for a proof.
  • Algorithmica - memory and data layout
    Sergey Slotinsupportapplication
    Read the memory hierarchy, cache and complexity-model chapters, then measure one contiguous-versus-linked and one hash-versus-ordered workload crossover.
  • NeetCode - unseen linear problems
    NeetCodeoptionalassessment
    Use only for two tag-hidden transfer problems after the AlgoMaster slice. Do not start another full roadmap or watch a solution before the attempt is complete.
  • Hypothesis documentation - Quickstart and stateful testing
    Hypothesissupportreference
    Follow Quickstart for @given strategies and the pytest combination, Configuring test settings for max_examples and derandomize, then Rule-based state machines (rule, precondition, invariant, run_state_machine_as_test) for randomized operation histories against dict and deque oracles.
  • CPython source - list and dict objects
    Python Software Foundationreferencereference
    Read list_resize in Objects/listobject.c for the growth formula and pattern comment, and the USABLE_FRACTION definition, perturbation-probing comment and dummy-entry handling in Objects/dictobject.c. Read the cited functions and comments only.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels