Skip to main content

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 Principles

Agent 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) space
Key problems: Longest Substring Without Repeating Characters, Minimum Window Substring, Max Sum Subarray of Size K.

2. 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) space
Key problems: Two Sum (sorted), 3Sum, Container With Most Water, Valid Palindrome.

3. 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) space
Key problems: Linked List Cycle, Find Middle, Palindrome Linked List, Happy Number.
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) space
Binary search on answer: When the answer is a value in a range and “can we achieve X?” is checkable in O(n) — binary search on X. Key problems: First Bad Version, Search in Rotated Array, Find Peak Element, Koko Eating Bananas (search on answer).

5. 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
Key problems: Merge Intervals, Insert Interval, Meeting Rooms I & II.
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) space
Key problems: Binary Tree Level Order Traversal, Word Ladder, Rotting Oranges, Number of Islands.
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)
DFS vs BFS decision: Use BFS for shortest path. Use DFS for exhaustive exploration, cycle detection, or when recursion maps naturally to the problem. Key problems: Number of Islands, Course Schedule (cycle detection), Path Sum, Word Search in Grid.

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.
Pruning: Add 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:
Bottom-up (tabulation) — iterative, fills table from base cases:
Design steps:
  1. Define dp[i] (or dp[i][j]) precisely in words.
  2. Write the recurrence relation.
  3. Identify base cases.
  4. Choose top-down or bottom-up.
Key problems: Coin Change, Longest Common Subsequence, 0/1 Knapsack, Edit Distance, Longest Increasing Subsequence.

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):
Key problems: Course Schedule I & II, Alien Dictionary, Minimum Height Trees.

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.
Key problems: Number of Connected Components, Graph Valid Tree, Accounts Merge, Redundant Connection.

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
Key problems: Kth Largest Element, Top K Frequent Elements, K Closest Points to Origin, Merge K Sorted Lists.
Problem shape: Search in a sorted-but-modified array (rotated, with duplicates, or searching for a boundary condition). Recognize it when: Sorted array with a twist — rotation, finding first/last occurrence, finding peak. Complexity: O(log n) time, O(1) space
Key problems: Search in Rotated Sorted Array, Find Minimum in Rotated Array, Find First and Last Position.

15. Monotonic Stack / Queue

Problem shape: “Next greater/smaller element”, “span of prices”, “sliding window max/min”. Recognize it when: For each element, you need to find the nearest element that is greater or smaller; or sliding window extremes. Complexity: O(n) time — each element pushed and popped at most once. O(n) space.
Key problems: Next Greater Element, Daily Temperatures, Sliding Window Maximum, Largest Rectangle in Histogram, Trapping Rain Water.