LeetCode Patterns
The 14 canonical algorithmic patterns that cover the majority of coding-interview problems. Each page has a generic template, real LeetCode example problems with difficulty, common mistakes, and FAQs — written for candidates who want to pattern-match, not memorize.
By Alex Chen, Founder of InterviewChamp.AI
Backtracking
The Backtracking pattern explores a decision tree by recursively trying each choice, recording it in the current path, and undoing it before trying the next branch. Pruning illegal partial states early collapses an apparent O(b^d) search into something tractable for small inputs. Typical runtime stays exponential (O(N!) or O(2^N)) with O(N) recursion-depth space.
8 example problems · Time O(N!)
Bit Manipulation
The Bit Manipulation pattern treats integers as fixed-width arrays of bits and uses XOR, AND, OR, and shifts to solve counting, parity, and uniqueness problems in O(n) time and O(1) extra space. XOR's self-cancelling property finds the lonely element in a duplicate sea; masking with (x & (x - 1)) clears the lowest set bit in one step.
8 example problems · Time O(n)
Cyclic Sort
Cyclic Sort places each value in an array of integers from a known range into its correct index by swapping it with whatever value is currently there. It is the canonical pattern for problems on arrays containing numbers in the range 1..n or 0..n-1 and runs in O(n) time with O(1) extra space.
6 example problems · Time O(n)
Dijkstra's Shortest Path
Dijkstra's algorithm computes the shortest path from a single source to every other vertex in a weighted graph with non-negative edge weights. It is the canonical answer to shortest-path interview questions — using a min-heap to always extract the next-closest unvisited vertex — and runs in O((V + E) log V) with a binary heap, which is fast enough for nearly every grid, graph, or network problem you will see.
8 example problems · Time O((V + E) log V) with a binary heap
Dynamic Programming on Grids
The Dynamic Programming on Grids pattern fills a 2D table where each cell's answer depends on a constant set of neighbors (usually up + left, or all four directions). It replaces an exponential recursion over grid paths with a single bottom-up pass, achieving O(m * n) time and O(m * n) space (or O(min(m, n)) with a rolling row).
7 example problems · Time O(m * n)
Dynamic Programming on Strings
The Dynamic Programming on Strings pattern compares two sequences (or a string against itself) by filling a 2D table dp[i][j] indexed by prefix lengths. Each cell extends a smaller subproblem by one character on either side, replacing exponential character-by-character branching with O(m * n) time and O(m * n) space.
8 example problems · Time O(m * n)
Fast and Slow Pointers
Fast and Slow Pointers (also called Floyd's Tortoise and Hare) advances two pointers through a sequence at different speeds, with the fast pointer moving two steps for every one step of the slow pointer. It detects cycles, finds middle elements, and locates start-of-cycle nodes in O(n) time and O(1) extra space.
7 example problems · Time O(n)
Fenwick Tree
A Fenwick Tree, also known as a Binary Indexed Tree (BIT), is a compact array structure that supports prefix-sum queries and point updates in O(log n) using only n+1 slots of memory. It is the minimal, fastest answer to the canonical mutable-prefix-sum problem and is preferred over a segment tree whenever the aggregate is sum or xor and lazy range updates are not required.
8 example problems · Time O(log n) per query, O(log n) per update, O(n log n) build (or O(n) with linear-time variant)
Greedy
The Greedy pattern builds an answer one step at a time by always taking the locally optimal choice, never reconsidering past decisions. It works when the problem has the greedy-choice property and optimal substructure, letting a single linear pass replace an exponential search. Typical runtime is O(n) or O(n log n) when sorting first, with O(1) extra space.
8 example problems · Time O(n log n)
In-Place Linked List Reversal
In-Place Linked List Reversal flips the direction of a singly linked list (or a sublist within it) by rewiring `next` pointers as you walk through the nodes, using three local pointers and no extra storage. The technique handles full reversal, sublist reversal, and k-group reversal in O(n) time with O(1) space.
7 example problems · Time O(n)
Intervals and Event Sweep
The Intervals and Event Sweep pattern converts a set of [start, end] intervals into a stream of +1 / -1 events sorted by time, then sweeps once to compute concurrency, conflict, or free-time questions. Sorting dominates at O(n log n); the sweep itself is O(n). It is the canonical move for meeting-room capacity, calendar conflicts, and 'find the gaps' problems.
8 example problems · Time O(n log n)
K-way Merge
K-way Merge combines K sorted lists or sequences into a single sorted output by maintaining a min-heap of the current head element from each list and repeatedly popping the smallest. It generalizes the two-way merge of merge sort to any number of inputs in O(N log K) time, where N is the total number of elements and K is the number of lists.
6 example problems · Time O(N log K)
KMP String Matching
The Knuth-Morris-Pratt (KMP) algorithm finds all occurrences of a pattern inside a text in O(n + m) time without ever backing up the text pointer. It does this by precomputing a failure function — an array that, for each prefix of the pattern, stores the length of the longest proper prefix that is also a suffix — and then using that table to skip redundant character comparisons on a mismatch.
8 example problems · Time O(n + m) where n is text length and m is pattern length
Memoization (Top-Down DP)
The Memoization pattern wraps a natural recursive solution with a cache keyed on the function's arguments, so each unique subproblem is solved exactly once. It is the top-down face of dynamic programming — write the recurrence first, then add the cache. Time drops to O(states * work-per-state); space is dominated by the cache plus the recursion stack.
8 example problems · Time O(n)
Merge Intervals
The Merge Intervals pattern sorts a list of intervals by start time and walks through them once, merging any interval whose start falls inside the running end of the previous interval. It handles overlap, gap, scheduling, and conflict problems in O(n log n) time dominated by the initial sort.
8 example problems · Time O(n log n)
Minimum Spanning Tree
A Minimum Spanning Tree (MST) is a subset of edges in a connected, undirected, weighted graph that connects all vertices with the minimum possible total edge weight and contains no cycles. Two canonical algorithms solve it: Kruskal's, which sorts edges and uses Union-Find to detect cycles, and Prim's, which grows the tree one vertex at a time using a min-heap. MST is the standard answer for 'connect all the things at minimum cost' problems.
8 example problems · Time O(E log E) for Kruskal (sort dominates); O((V + E) log V) for Prim with a binary heap
Modified Binary Search
Modified Binary Search adapts the classic logarithmic search to inputs that are sorted-then-rotated, infinite, two-dimensional, or organized around an answer-space rather than a literal value. It compresses an O(n) scan into O(log n) by halving the search range on every iteration, using O(1) space.
9 example problems · Time O(log n)
Monotonic Stack
The Monotonic Stack pattern maintains a stack whose elements stay in strictly increasing or decreasing order. When a new element violates that order, the stack pops until the order is restored, and each pop emits an answer for the popped element. This drops Next Greater Element and span-style problems from O(n^2) to O(n) because each item is pushed and popped at most once.
8 example problems · Time O(n)
Prefix Sum
The Prefix Sum pattern precomputes a cumulative running total of an array so any contiguous range sum can be answered in O(1) time via a single subtraction. Combined with a hash map of seen prefix sums, it counts subarrays with a target sum in a single linear pass. Build is O(n) time and O(n) space; each subsequent range query is O(1).
8 example problems · Time O(n)
Segment Tree
A Segment Tree is a balanced binary tree built over an array where each internal node summarizes a contiguous range of the underlying data — typically a sum, min, max, gcd, or any associative function. It replaces O(n) range queries and O(n) updates with O(log n) for both, which is the standard answer whenever an interviewer combines range-aggregate queries with point updates on the same input.
8 example problems · Time O(log n) per query, O(log n) per update, O(n) build
Sliding Window
The Sliding Window pattern maintains a contiguous range of elements in an array or string and expands or contracts that range as it scans the input once. It replaces nested loops that re-scan the same subarray repeatedly, turning O(n^2) brute-force solutions into O(n) by reusing work between iterations.
8 example problems · Time O(n)
Subsets
The Subsets pattern enumerates every combination, permutation, or arrangement of a small set of elements by either iteratively extending an existing list of subsets with each new element or by recursing through a decision tree (include / exclude). It powers backtracking problems on combinations, permutations, and string letter cases in O(n * 2^n) time and O(n * 2^n) space.
8 example problems · Time O(n * 2^n)
Top K Elements
The Top K Elements pattern uses a heap of size k to track the largest, smallest, or most frequent values in a stream or array without sorting the whole input. It answers "top k" and "k closest" questions in O(n log k) time and O(k) space, which beats the O(n log n) cost of a full sort when k is small.
8 example problems · Time O(n log k)
Topological Sort
Topological Sort produces a linear ordering of the vertices in a directed acyclic graph such that for every edge u -> v, u appears before v in the order. It is the canonical pattern for dependency resolution, course scheduling, and build ordering problems, running in O(V + E) time using either Kahn's BFS algorithm or a DFS post-order traversal.
7 example problems · Time O(V + E)
Tree Breadth-First Search
Tree BFS visits a tree level by level using a queue, processing every node at depth d before any node at depth d+1. It is the canonical pattern for level-order traversal, shortest-path-in-tree problems, and any question whose answer depends on horizontal slices of the tree, in O(n) time and O(w) space where w is the maximum width.
8 example problems · Time O(n)
Tree Depth-First Search
Tree DFS explores a tree by going as deep as possible along one branch before backtracking, traditionally implemented through recursion or an explicit stack. It is the workhorse pattern for path problems, subtree aggregates, validation checks, and any computation whose answer depends on root-to-leaf information, running in O(n) time and O(h) space where h is tree height.
9 example problems · Time O(n)
Trie
The Trie (Prefix Tree) pattern stores a set of strings in a rooted tree where each edge spells one character and each path from the root spells a prefix. Insertions and lookups run in O(L) time, where L is the word length, independent of how many words the trie holds. It powers fast prefix queries, autocomplete, and word-search-on-a-grid problems.
7 example problems · Time O(L)
Two Heaps
The Two Heaps pattern maintains a max-heap for the lower half of a stream of values and a min-heap for the upper half, balanced so their sizes differ by at most one. It answers running-median, sliding-window-median, and IPO-style scheduling problems in O(log n) per insert with O(n) total space.
5 example problems · Time O(log n)
Two Pointers
The Two Pointers pattern uses two index variables that traverse a sorted array or string, usually moving toward each other from opposite ends or in the same direction at different speeds. It replaces nested loops on sorted input, dropping a brute-force O(n^2) solution down to O(n) time and O(1) extra space.
8 example problems · Time O(n)
Union-Find
The Union-Find (Disjoint Set Union) pattern maintains a partition of N elements into non-overlapping groups, supporting two operations: find(x) returns the group representative, and union(x, y) merges two groups. With path compression and union-by-rank, both operations run in near-constant amortized time, formally O(alpha(N)) where alpha is the inverse Ackermann function.
7 example problems · Time O(alpha(N))