Common Problem Solving Patterns (Sliding Window, Two Pointers, etc.)
Common Problem Solving Patterns (Sliding Window, Two Pointers, etc.)
- Sliding Window: maintain a window with
O(1)updates to solve subarray/substring problems - Two Pointers: converge/diverge for pairs/dups in sorted data
- Fast & Slow Pointers: cycle detection (Floyd), middle of list
- Binary Search on Answer: search a monotonic answer space
// Sliding window: longest substring with <= K distinct chars
function longestKDistinct(s, K){
const freq=new Map(); let best=0, l=0
for(let r=0;r<s.length;r++){
freq.set(s[r],(freq.get(s[r])||0)+1)
while(freq.size>K){
const c=s[l++]; const v=freq.get(c)-1; v?freq.set(c,v):freq.delete(c)
}
best=Math.max(best, r-l+1)
}
return best
}
Recognizing patterns reduces time-to-solution dramatically and guides complexity expectations.

