Patterns
21 patterns grouped by family. Search by signal to practise the lookup you actually need in an interview.
Showing all 21 patterns
Array Sweeps
5 patternsYou move indices along a line.
- Sliding Windowcode
Longest/shortest/max/min contiguous subarray or substring
Grow right, shrink left while the window is invalid.
- Two Pointerscode
Sorted array, find a pair/triplet hitting a target
Converge left/right pointers.
- Prefix Sumcode
Range sums, or subarray sum equals K (with negatives)
Precompute cumulative sums; range = P[j]-P[i]; pair with a hashmap.
- Cyclic Sort / Index-as-Hash
Values in 1..n; find duplicate/missing in O(1) space
The array is its own hash table.
- Intervalscode
Merge/insert overlapping intervals, meeting rooms
Sort by start, merge when curr.start <= prev.end.
Binary Search
2 patternsSorted input, or an O(log n) requirement.
Linear Helpers
3 patternsProcess a sequence with one helper structure.
- Stackcode
Matching/balance/nesting, undo last
Push openers, pop and verify on closers.
- Monotonic Stackcode
Next greater/smaller, nearest larger to the right
Keep an increasing/decreasing stack; each pop resolves an answer.
- Fast & Slow Pointerscode
Linked list cycle/middle/nth-from-end
Two pointers at different speeds (tortoise and hare).
Heap
1 patternsKeep only the important few.
Trees & Graphs
5 patternsTraverse a structure.
- Tree BFScode
Level order, min depth, width per level
Process one whole level at a time with a queue.
- Tree DFScode
Root-to-leaf path, subtree logic, validation
Recurse; pass bounds/state down.
- Graph BFS/DFScode
Islands/regions in a grid, shortest steps
Flood-fill with a visited set; BFS for shortest.
- Topological Sortcode
Prerequisites, ordering, can-you-finish, dependencies
Indegree + queue (Kahn); leftovers mean a cycle.
- Union-Findcode
Connected groups, friend circles, merge accounts
Union elements, count distinct roots; path compression + rank.
Recursion Family
4 patternsExplore possibilities or optimize.
- Backtrackingcode
Generate all subsets/permutations/combinations
Choose, recurse, un-choose; prune early.
- 1-D Dynamic Programmingcode
Number of ways / min cost / max value with overlapping choices
Define state, transition, base case.
- 2-D Dynamic Programmingcode
Two strings: edit distance, LCS, grid paths
Grid of subproblems indexed by (i, j).
- Palindrome DPcode
Palindromic substrings or longest palindromic subsequence
Expand around each center, or fill a 2-D table.
Hashmap (sidekick)
1 patternsAlways-on tool to turn O(n^2) into O(n).