Two Pointers & Sliding Window
Replace nested loops over arrays and strings with two coordinated indices or a moving window.
4 objectives 6 steps about 125 min
Check what you know
The lessons are coming later. The knowledge check is ready now.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Solve pair and triple problems on sorted arrays with converging pointers (pair sum, 3-sum, container with most water) and justify why no valid candidate is skipped.
- Apply fixed-size sliding windows to compute running aggregates in O(n).
- Apply variable-size windows with hash-based counts to longest and shortest substring or subarray problems, stating the window invariant.
- Count the subarrays or substrings that satisfy a condition with a variable window, adding right - left + 1 at each step, and count 'exactly k' cases as at-most(k) minus at-most(k - 1).
Lesson plan
6 steps, about 125 min · 0 of 5 lessons available so far
- Two Indices, One Pass Concept · 20 min · coming later
- Why Converging Pointers Miss Nothing Worked example · 25 min · coming later
- Fixed Windows and Running Aggregates Worked example · 15 min · coming later
- Lab: Variable Windows with Counts Lab · 30 min · coming later
- Counting Windows: At Most k and Exactly k Worked example · 20 min · coming later
- Check: Pointer and Window Problems Knowledge check · 8 questions
Practise it
Solve 3-sum without duplicate triples, maximum average subarray of length k, longest substring without repeating characters, and minimum window containing all target characters; write the invariant for each and meet O(n) (O(n^2) for 3-sum) on the hidden tests. Finally, count the subarrays with exactly k distinct values as at-most(k) minus at-most(k - 1) and match an O(n^2) count on random inputs.
References
Hard prerequisites
Unlocks
Nothing depends on this skill yet.
On these roadmaps
Progress and evidence for this skill are shared across all of them.