Muscle-Memory Templates
The base code you write without thinking. Don't just read these — type each one from memory until it's automatic. Then solving becomes “which template + what tweak” instead of “how do I start.”
24 templates · 8 categories
Graph / Grid Traversal
BFS · DFS · the bread and butterThese appear in at least one of every couple of coding rounds. Number of Islands, flood fill, shortest path, level-order — all reduce to BFS or DFS with small tweaks. Memorize the grid directions array and the visited-set pattern cold.
Binary Search
the template that ends off-by-one bugsMost people get binary search wrong under pressure because of boundary conditions. Memorize ONE template and adapt it. The key decisions:
< vs <=, and whether to do mid+1 / mid-1 / mid. The "search on answer" variant is a frequent senior-level twist.Two Pointers & Sliding Window
O(n) where brute force is O(n²)Two pointers turns nested loops into a single pass. Sliding window is the variable-size version — grow the right edge, shrink the left when a constraint breaks. Memorize the window skeleton; it solves a huge family of substring/subarray problems.
Heap / Priority Queue
top-K, merge-K, running medianWhenever you see "K-th largest", "top K", "merge K", or "closest K" — reach for a heap. In Java,
PriorityQueue is a min-heap by default. Memorize the comparator syntax for max-heap and custom objects.Dynamic Programming
1D · 2D · the recurrence skeletonsDP is recognizing the recurrence, then choosing top-down (memo) or bottom-up (table). Memorize both skeletons. The hard part is defining the state — these templates give you the scaffolding so you only think about the transition.
Backtracking
subsets · permutations · combinationsOne skeleton powers all backtracking: choose → explore → un-choose. Subsets, permutations, combinations, N-Queens, word search — same shape. Memorize the template and the three variations (start index, used array, in-place swap).
Core Structures
Union-Find · Trie · the ones to know coldTwo structures appear so often they're worth memorizing as complete units: Union-Find (connectivity, cycles, Kruskal) and Trie (prefix problems). Writing these flawlessly under pressure signals strong fundamentals.
Java Utilities
syntax you must not fumbleThe Java-specific syntax that wastes time if you blank on it. Sorting with comparators, the HashMap idioms, char/int conversions. None of this is algorithmic — but fumbling it on the whiteboard kills momentum. Drill until automatic.