Sliding Window & Two Pointers Master Map π―
Overview
- Core Techniques
- Sliding Window (
SubstringSlidingWindow API Kernel) - Two Pointers (
TwoPointersTraversal & FastSlowPointers & TwoPointerPartition) - Use Cases
- Substring / subarray optimization
- In-place array modification
- Pair / k-sum / palindrome / merge
- Cycle detection
- Roadmaps
- Sliding Window:
sliding_window_path - Two Pointers:
two_pointers_path - General:
neetcode_150, blind_75, grind_75, leetcode_top_100
Sliding Window Patterns π
Core Concept
- API Kernel:
SubstringSlidingWindow - Maintain window
[left, right] over sequence - State: hash map / counters / running sum
- Invariant: property that must hold for current window
- Operations
- Expand:
right++ - Contract:
left++ while invariant violated (or while still valid, if minimizing) - Complexity
- Time: \(O(n)\)
- Space: typically \(O(\sigma)\) or \(O(K)\)
Canonical Template
left = 0
state = init_state()
answer = init_answer()
for right, x in enumerate(seq):
add(state, x) # expand
while invalid(state): # or while valid(state) when minimizing
remove(state, seq[left])
left += 1
answer = update(answer, left, right, state)
return answer
1. Unique Characters Window (Base) π
- Pattern:
sliding_window_unique - Invariant: all chars in window are unique
- State:
last_seen_index[char] - Optimization: jump
left instead of while-loop - Problem:
- LeetCode 3 - Longest Substring Without Repeating Characters
- Snippet:
0003_base.md - Family:
substring_window - Topics:
string, hash_table, sliding_window - Roadmaps:
neetcode_150, blind_75, grind_75, leetcode_top_100, sliding_window_path - β
Best first sliding window problem
2. At Most K Distinct Characters
3. Frequency Cover (Min / Exact Cover) π§¬
- Pattern:
sliding_window_freq_cover - Invariants:
- Cover: window has at least required freq for each char in
t - Often minimize length once cover is achieved
- State:
need_frequency (from pattern string) have_frequency or window_frequency chars_satisfied vs chars_required - Problems:
- LeetCode 76 - Minimum Window Substring
- Min-length window containing all chars of
t
- LeetCode 438 - Find All Anagrams in a String
- All positions where window is an anagram of
p
- LeetCode 567 - Permutation in String
- Boolean: does any permutation of
s1 appear in s2?
- Snippets:
0076_min_window.md 0438_anagrams.md 0567_permutation.md - Families:
substring_window - Topics:
string, hash_table, sliding_window
Sub-Variants
- Fixed-size window (anagram / permutation)
- Window size =
len(pattern) - Slide, maintain counts, compare or track
chars_matched - Variable-size window (min window)
- Expand until all requirements met
- Then contract while still valid to minimize
4. Cost-Bounded / Sum-Bounded Window π°
- Pattern:
sliding_window_cost_bounded - Invariant: numeric property (sum / cost) respects constraint
- State: scalar sum or cost
- Example:
- LeetCode 209 - Minimum Size Subarray Sum
- Invariant:
window_sum β₯ target - Goal: minimize window length
- Snippet:
0209_min_subarray.md - Family:
substring_window - Topics:
array, sliding_window, prefix_sum, binary_search (alt solution)
5. Sliding Window Quick Comparison π
- Snippet:
_comparison.md - Table Summary
| Problem | Invariant | State | Window Size | Goal |
| LeetCode 3 | All unique | last index map | Variable | Maximize |
| LeetCode 340 | β€ K distinct | freq map | Variable | Maximize |
| LeetCode 76 | covers t | need/have maps | Variable | Minimize |
| LeetCode 567 | exact match | freq map | Fixed | Exists? |
| LeetCode 438 | exact match | freq map | Fixed | All positions |
| LeetCode 209 | sum β₯ target | integer sum | Variable | Minimize |
6. When to Use Sliding Window β
- Snippet:
_decision.md - β
Indicators
- Answer is a contiguous substring/subarray
- Want to minimize/maximize length/value
- Can incrementally update state when
left/right move in \(O(1)\) - β Avoid when
- Need non-contiguous selection β DP / combinatorics
- State depends on global information β prefix sums + binary search, etc.
- Flow:
- Contiguous? β Yes β Incremental state? β Yes β Sliding window
- Roadmap:
sliding_window_path
7. Sliding Window Templates Cheat Sheet
- Snippet:
_templates.md - Maximize variable window
- Minimize variable window
- Fixed-size window
Two Pointers Patterns βοΈ
Core Concept
- Algorithm:
two_pointers (technique) - API Kernels:
TwoPointersTraversal FastSlowPointers TwoPointerPartition MergeSortedSequences - Sub-Patterns
- Opposite pointers
- Same-direction (reader/writer)
- Fastβslow (cycle / midpoint)
- Partition / Dutch flag
- Multi-sum enumeration
- Merge two sorted sequences
1. Opposite Pointers (Two-End) β¬
οΈβ‘οΈ
2. Same-Direction Pointers (Reader/Writer) βοΈ
3. FastβSlow Pointers (Cycle / Midpoint) π’π
4. Partitioning / Dutch National Flag π©
5. Multi-Sum Enumeration (3Sum, 4Sum) β
- Patterns:
two_pointer_three_sum two_pointer_k_sum - Strategy:
- Sort array
- Fix one or more indices with outer loops
- Use opposite pointers internally
- Deduplicate by skipping equal neighbors
- Problems:
- LeetCode 15 - 3Sum
- LeetCode 16 - 3Sum Closest
- Family:
multi_sum_enumeration - Topics:
array, sorting, two_pointers
6. Merge Sorted Sequences π
7. Two Pointers Comparison & Decision π
- Snippets:
_comparison.md _decision.md _templates.md _mapping.md - Comparison Table (summary)
| Pattern | Init | Movement | Use Case |
| Opposite | 0, n-1 | inward | sorted pairs, palindromes, container |
| Same-Direction | read, write | forward | in-place remove/dedup/compact |
| FastβSlow | slow=fast=head | 1Γ vs 2Γ | cycles, midpoints |
| Partition | low, mid, high | by value | Dutch flag, parity, quickselect |
| Merge | i, j | advance smaller | merge sorted sequences |
- Decision Hints
- Sorted & need pair/tuple? β Opposite / multi-sum
- In-place modification? β Same-direction writer
- Cycle / midpoint? β Fastβslow
- Partition by property? β Dutch flag / two-way partition
- Merge sorted data? β Merge pattern
Linked List Manipulation (Bonus) π
- API Kernels:
LinkedListInPlaceReversal FastSlowPointers - Key Patterns:
linked_list_full_reversal linked_list_partial_reversal linked_list_k_group_reversal - Representative Problem:
- LeetCode 25 - Reverse Nodes in k-Group
BFS Grid Wavefront (Bonus Anchor) π
- API Kernel:
GridBFSMultiSource - Pattern:
grid_bfs_propagation - Problem:
- LeetCode 994 - Rotting Oranges
- Family:
graph_wavefront, matrix_traversal - Shows contrast: when BFS is more natural than two pointers/sliding window
Learning Path Checklist β
Sliding Window Path
Two Pointers Path
Interview-Oriented Highlights πΌ
- Must-know Sliding Window:
- LeetCode 3, LeetCode 209, LeetCode 76, LeetCode 567, LeetCode 438
- Must-know Two Pointers:
- Opposite: LeetCode 11, LeetCode 15, LeetCode 125
- Writer: LeetCode 26, LeetCode 283
- FastβSlow: LeetCode 141, LeetCode 142
- Partition: LeetCode 75, LeetCode 215
- Merge: LeetCode 21, LeetCode 88