Algorithmic Patterns & Solving Techniques
Technical interviews test repeatable problem-solving techniques rather than memorized solutions. Explore the canonical taxonomy of algorithmic patterns, their core intuition, and vetted practice problems.
Arrays
3 patternsArray Rotation via Triple Reversal
Rotate an array in place by reversing the whole array and then reversing its two constituent segments.
Kadane's Algorithm
Track the best subarray sum ending at the current index, resetting to zero whenever the running sum turns negative.
Prefix Sum
Precompute running sums (or products) so range queries or comparisons become O(1) instead of re-scanning.
Backtracking
6 patternsBacktracking - Combinations
Build fixed- or variable-length combinations by choosing the next element from a remaining candidate pool.
Backtracking - Grid Path Search
DFS with backtracking over a 2D grid, marking/unmarking visited cells while searching for a path matching a target.
Backtracking - Partition/Cut Points
Build the recursion tree by choosing where to make the next cut/partition point, rather than an include/exclude decision per element.
Backtracking - Permutations
Build all orderings of a set by swapping/marking used elements at each recursive level.
Backtracking - Subsets (Include/Exclude)
Build the recursion tree by deciding, for each element in turn, whether to include it in the current subset.
N-Queens Style Constraint Backtracking
Place items one row/column at a time, pruning branches immediately when a placement violates a global constraint set.
Binary Search
3 patternsBinary Search (Classic Lookup)
Standard binary search over a sorted array (or a local monotonic comparison) to locate a target index or boundary.
Binary Search on a Rotated Array
Binary search adapted to a rotated sorted array by determining which half is still sorted at each step.
Binary Search on the Answer
Binary search over the space of possible answer values, using a feasibility check to decide which half to keep.
Bit Manipulation
2 patternsDivide & Conquer
1 patternDynamic Programming
12 patterns0/1 Knapsack
DP where each item may be used at most once, choosing a subset that hits or approaches a target.
Circular Array DP
Handle a circular adjacency constraint by reducing to two linear DP passes that each exclude one end.
Expand Around Center
Treat every index (and gap between indices) as a palindrome center and expand outward while it still matches.
Grid / 2D Path DP
DP over a 2D grid where each cell's value depends on cells reachable by the allowed moves (down/right, etc.).
Interval DP
DP over subarray/substring ranges [i, j], combining results of smaller sub-ranges to solve larger ones.
Linear 1D DP
A DP recurrence over a single sequence where each state depends on a small fixed window of previous states.
Longest Increasing Subsequence DP
DP (optionally with binary search) tracking the best increasing subsequence length ending at each index.
Minimax Game State DP
DP where state represents game configuration (remaining piles, positions, turns) and we compute win/loss from each state assuming optimal play from both players.
State Machine DP
DP tracking which of several explicit states (e.g. holding/not-holding stock, in/out of cooldown) you're in at each step.
String Alignment / Subsequence DP
2D DP over two string indices to compare, align, or count subsequences/substrings between them.
Take/Skip Adjacent-Constraint DP
DP where taking an element forbids taking its immediate neighbor, tracking best-with/without-current at each step.
Unbounded Knapsack
DP where each item/coin can be reused an unlimited number of times while building toward a target.
Graphs
10 patternsBFS Shortest Path (Unweighted)
Standard BFS where each edge has equal weight, so the first time a node is reached is guaranteed shortest.
Bounded-Hop Shortest Path (Bellman-Ford Style)
Relax edges for a limited number of rounds (bounding the number of hops/stops) rather than running unbounded Dijkstra, since the constraint makes plain Dijkstra unsound.
Dijkstra's Shortest Path
Priority-queue-driven shortest path on a weighted graph with non-negative edges, greedily finalizing the closest node.
Flood Fill
Recursively (or iteratively) spread a fill from a starting cell to all connected cells matching a condition.
Graph DFS Traversal
DFS across an explicit or implicit graph (adjacency list) to visit, clone, or reconstruct connected structure.
Grid DFS Traversal
DFS across grid cells following adjacency (usually 4-directional), typically to explore or measure a connected region.
Minimum Spanning Tree (Prim's/Kruskal's)
Build a minimum-weight tree connecting all nodes, either by growing from a frontier (Prim's) or sorting edges and using union-find (Kruskal's).
Multi-Source BFS
Seed the BFS queue with multiple starting nodes simultaneously so distances propagate from all sources in lockstep.
Topological Sort
Order nodes of a DAG so every directed edge points from earlier to later, via DFS post-order or Kahn's algorithm.
Union-Find / Disjoint Set
Maintain disjoint sets with union and find operations to detect connectivity or cycles as edges are processed.
Greedy
6 patternsBoyer-Moore Voting Algorithm
Maintain a single candidate and a counter, incrementing on a match and decrementing otherwise, to find a majority element in one pass with O(1) space.
Greedy Farthest-Reach Tracking
Greedily track the farthest index reachable so far while scanning left to right to decide feasibility or minimum jumps.
Greedy Interval Scheduling
Sort intervals by end time and greedily keep/skip each one to maximize non-overlapping selections.
Greedy Min/Max Range Tracking
Track a running [lower, upper] bound of possible values while scanning, collapsing or rejecting when the range becomes invalid.
Greedy Single-Pass Decision
Make a locally optimal choice while scanning once left to right, where the specific decision rule is simple enough not to warrant its own named pattern.
Greedy Two-Pass Comparison
Scan left-to-right then right-to-left (or vice versa), each pass enforcing a local ordering constraint against the neighbor.
Hashing
3 patternsHashmap Existence / Complement Lookup
Use a hashmap or set purely to answer 'have I seen this before' or 'does the complement exist', not to count occurrences.
Hashmap Frequency / State Counting
Track counts or per-key state (character tallies, bijective mappings) in a single pass with a hashmap, then compare or query those counts.
Hashmap Grouping by Canonical Key
Bucket items together under a derived canonical key (e.g. sorted string) using a hashmap of lists.
Heap
3 patternsHeap for Top-K / Kth Element
Maintain a fixed-size heap to track the k largest/smallest/most-frequent elements seen so far.
Quickselect
Use a partition step (like quicksort) to find the kth largest/smallest element in average O(n) without fully sorting.
Two Heaps (Median Maintenance)
Balance a max-heap of the lower half against a min-heap of the upper half to maintain a running median.
Intervals
1 patternLinked List
5 patternsFast/Slow Pointers (Cycle & Midpoint)
A tortoise-and-hare pair of pointers moving at different speeds to detect a cycle or find a midpoint/kth-from-end node.
Hashmap Node-to-Node Mapping
Use a hashmap as an old-object-to-new-object identity map to reconstruct a structure with internal cross-references (e.g. cloning a list with random pointers).
Linked List In-Place Reversal
Rewire next-pointers to reverse a linked list or a sublist in place without extra storage.
Linked List Merge (K-Way)
Merge two or more already-sorted linked lists into one sorted list by repeatedly picking the smallest head.
Linked List Partition / Splice
Splice a linked list into separate chains by a pivot condition, then reconnect them in the required order.
Math
4 patternsBig-Number Arithmetic Simulation
Simulate elementary-school arithmetic (add/multiply) digit-by-digit with carries, because the operands exceed native integer range.
Digit Manipulation Simulation
Peel off and reconstruct a number digit-by-digit to reverse it, check a property, or apply an increment.
Game Parity Reasoning
Determine game outcome from simple parity, count-based, or mathematical invariants without full state DP (e.g., whether count is even/odd, modulo-based reasoning).
Number Theory
Apply a number-theoretic property (factor counting, GCD/slope reasoning) rather than a general-purpose algorithm.
Matrix
1 patternSliding Window
2 patternsSliding Window (Fixed Size)
Slide a window of constant size across the input, incrementally updating window state as it moves.
Sliding Window (Variable Size)
Expand and shrink a window's right/left edges based on a validity condition to find an optimal-length substring/subarray.
Stack
4 patternsMonotonic Decreasing Stack
Maintain a stack that only ever decreases, popping elements when a larger one arrives to find next-greater relationships.
Monotonic Deque
Maintain a double-ended queue of candidate indices in monotonic order to answer sliding-window max/min in O(1) amortized.
Monotonic Increasing Stack
Maintain a stack that only ever increases, popping when a smaller element arrives to bound a region (e.g. largest rectangle).
Stack-Based Matching / Evaluation
Use a stack to match nested symbols or evaluate an expression by pushing/popping in the correct order.
Strings
2 patternsMulti-Pass String Construction
Build an output string through several structured passes or an explicit layout algorithm, rather than one linear scan.
String Index Scanning
A single linear pass over string indices (with simple lookups/comparisons) to extract or convert a value.
Trees
12 patternsBST Ordering Property
Exploit the left-less-than-node-less-than-right invariant of a BST to prune search space or produce sorted output.
Binary Indexed Tree (Fenwick Tree)
Use a BIT/Fenwick tree to answer prefix sum queries or range queries with point updates in O(log n) time, typically when the operation is associative and invertible.
Complete Tree Structural Binary Search
Exploit a tree's complete (heap-shaped) structure to binary search for where the last level ends, unrelated to BST ordering.
Generic Recursive Tree DFS
Plain recursive depth-first traversal used to transform or visit every node, where no more specific tree pattern applies.
Lowest Common Ancestor
Find the deepest node that is an ancestor of two given nodes, via recursive search or BST-property comparison.
Segment Tree Range Queries
Build a segment tree to answer range queries (sum, min, max, etc.) or perform range updates in O(log n) time, often with lazy propagation.
Tree BFS / Level-Order Traversal
Process a tree level-by-level using a queue, tracking level boundaries as needed.
Tree Height / Balance Check
Compute subtree heights bottom-up during DFS to check depth or balance conditions, often with early termination.
Tree Path Value Accumulation
Carry a running value down (or aggregate a value up) a root-to-leaf or arbitrary path during DFS.
Tree Reconstruction from Traversals
Rebuild a binary tree from two given traversal orders by using one to locate roots and the other to size subtrees.
Tree Serialization / Deserialization
Encode a tree into a linear representation (e.g. preorder with null markers) and decode it back into the same structure.
Tree Structural Comparison
Recursively compare two trees (or a tree against a mirrored version of itself) node-by-node for structural/value equality.
Tries
1 patternTwo Pointers
3 patternsSort Then Two Pointers
Sort the input first, then fix one element and use two pointers over the remainder to find combinations meeting a target.
Two Pointers (Opposite Ends)
Start pointers at both ends of a sorted or symmetric structure and move them toward each other based on a comparison.
Two Pointers (Same Direction)
A read/write or slow/fast pair of pointers moving the same direction through a sequence, compacting or scanning in place.