Algorithmic Patterns
15 pattern families that cover ~90% of algorithm problems. For each: problem shape, recognition trigger, complexity, and template. See also: Code Quality Heuristics, Software Design PrinciplesAgent Trigger
Apply when: Solving a coding/interview-style problem, choosing a traversal or search strategy, or optimizing a brute-force solution. Rule of thumb: Match the problem shape to a pattern family (sliding window, two pointers, BFS/DFS, DP, etc.) before writing code.Pattern Recognition Table
1. Sliding Window
Problem shape: Max/min/count over a contiguous subarray or substring of variable or fixed size. Recognize it when: “longest/shortest subarray where…”, “substring with at most K distinct…” Complexity: O(n) time, O(1) or O(k) space2. Two Pointers
Problem shape: Pair/triplet search in sorted array, palindrome check, in-place array manipulation. Recognize it when: Sorted input + “find two elements that sum to X”, or “remove duplicates in-place”. Complexity: O(n) time, O(1) space3. Fast & Slow Pointers (Floyd’s)
Problem shape: Linked list cycle, find middle, find k-th from end. Recognize it when: Linked list + “detect cycle” or “find middle without knowing length”. Complexity: O(n) time, O(1) space4. Binary Search
Problem shape: Sorted data; find a value, boundary, or answer by eliminating half the search space. Recognize it when: “O(log n) search”, sorted array, or “find minimum X such that condition holds” (binary search on answer). Complexity: O(log n) time, O(1) space5. Merge Intervals
Problem shape: Overlapping ranges — merge, insert, or count non-overlapping. Recognize it when: Input is a list of[start, end] intervals; “merge all overlapping”.
Complexity: O(n log n) time (sort dominates), O(n) space
6. BFS (Breadth-First Search)
Problem shape: Shortest path in unweighted graph; level-order traversal; “minimum steps to reach”. Recognize it when: “minimum number of moves/steps”, level-by-level processing, unweighted shortest path. Complexity: O(V + E) time, O(V) space7. DFS (Depth-First Search)
Problem shape: Explore all paths, tree/graph traversal, detect cycles, find connected components. Recognize it when: “find all paths”, “does a path exist”, backtracking exploration. Complexity: O(V + E) time, O(V) space (call stack)8. Backtracking
Problem shape: Generate all valid combinations, permutations, or arrangements subject to constraints. Recognize it when: “find all…”, “generate all…”, constraint satisfaction (N-Queens, Sudoku). Complexity: O(2^n) or O(n!) — inherently exponential; pruning reduces constant factor.if not is_valid(choice): continue before recursing. This is where all the performance lives.
Key problems: Permutations, Subsets, N-Queens, Generate Parentheses, Palindrome Partitioning.
9. Dynamic Programming
Problem shape: Optimal value (min/max count) where the problem breaks into overlapping subproblems. Recognize it when: “minimum cost to…”, “number of ways to…”, “longest subsequence/substring”. Complexity: O(n²) typical; O(n) for 1D DP; O(n·m) for 2D; space often reducible. Two approaches: Top-down (memoization) — natural recursion + cache:- Define
dp[i](ordp[i][j]) precisely in words. - Write the recurrence relation.
- Identify base cases.
- Choose top-down or bottom-up.
10. Greedy
Problem shape: Optimization where the locally optimal choice at each step yields a globally optimal result. Recognize it when: Sorting by one dimension then greedily selecting; problems where you can prove no future choice can improve a current decision. Complexity: Varies; often O(n log n) due to sort. Proof obligation: Before applying greedy, verify the greedy choice property holds. Greedy fails when future choices can invalidate current ones — use DP in that case. Key problems: Jump Game, Gas Station, Meeting Rooms II, Fractional Knapsack, Interval Scheduling.11. Topological Sort
Problem shape: Linear ordering of nodes in a DAG respecting directed edges (dependencies before dependents). Recognize it when: “prerequisites”, “task ordering”, “can you complete all courses”. Complexity: O(V + E) time and space Kahn’s Algorithm (BFS-based):12. Union-Find (Disjoint Set Union)
Problem shape: Dynamic connectivity — group elements, check if two elements are connected, detect cycles in undirected graph. Recognize it when: “connected components”, “are X and Y in the same group”, “does adding this edge create a cycle”. Complexity: O(α(n)) ≈ O(1) per operation with path compression + union by rank. O(n) space.13. Top K Elements (Heap)
Problem shape: Find the k largest, k smallest, or k most frequent elements without full sort. Recognize it when: “k largest/smallest”, “k closest”, “k most frequent”. Complexity: O(n log k) time, O(k) space — better than O(n log n) sort when k << n. Strategy:- K largest → min-heap of size k (evict smallest when heap exceeds k)
- K smallest → max-heap of size k (evict largest when heap exceeds k)
- K most frequent → count with hash map, then heap on counts