Sliding Window: The Pattern Behind Every Substring Question
The two-pointer playbook introduced the sliding window as one pattern among five. This post gives it the full treatment, because it is the pattern interviewers escalate through: the Easy fixed-size version, the Medium variable-size version, and the Hard frequency-constrained version are the same loop with a different constraint. Learn the loop once and the escalation is just a harder rule to maintain. The loop is: a window [l, r] where r expands every step and l shrinks only until the window satisfies the constraint again. The window is always valid when the shrink loop finishes — that invariant is the whole technique. And it is O(n) for a reason you can state in one sentence: l and r only ever move right, so each index enters the window once and leaves it once. No index is ever revisited, no matter how nested the code looks. I checked the bound empirically: across 2,000 random strings, the total shrink steps in the longest-substring loop never exceeded n. ...