Coding patterns for interviews
Most interview problems are variations on a dozen reusable patterns — learn the patterns, not the problems.
Instead of memorizing hundreds of problems, strong candidates recognize a small set of patterns: sliding window and two pointers for arrays, fast & slow pointers for linked lists, merge intervals for ranges, BFS/DFS for graphs and trees, binary search for sorted or monotonic spaces, top-K with heaps, dynamic programming for overlapping subproblems, and backtracking for combinatorial search. Each pattern comes with a trigger — a signal in the problem that tells you to reach for it.
Sliding window
Reach for it when a problem asks about a contiguous subarray or substring — longest, shortest, or a sum/count over a run of elements. Instead of re-examining every window from scratch (which is quadratic), you slide one window across the data, expanding the right edge to include new elements and shrinking the left edge when a constraint breaks. This turns many O(n²) scans into a single O(n) pass.
Two pointers
Reach for it when the data is sorted or you need to find a pair, triplet, or partition. Two indices move through the array — either converging from both ends (as in two-sum on a sorted array) or advancing together at different speeds — so you replace a nested loop with a single linear sweep. The sortedness is what lets you decide which pointer to move without missing an answer.
Fast & slow pointers
Reach for it on linked lists or cyclic sequences. One pointer advances two steps while another advances one; if there is a cycle they eventually meet, and when the fast pointer reaches the end the slow one sits at the middle. This 'tortoise and hare' idea detects loops, finds a list's midpoint, and locates a cycle's start — all in one pass and constant extra space.
Merge intervals
Reach for it whenever the input is a set of ranges — meeting times, booked rooms, overlapping segments. Sort the intervals by start, then walk them once, merging any that overlap with the current running interval and emitting it when the next one is disjoint. Sorting first is the key move: it guarantees that overlaps are always adjacent, so a single linear pass resolves the whole set.
BFS / DFS traversal
Reach for these on any tree or graph. Breadth-first search uses a queue to explore level by level, which is what you want for shortest paths in unweighted graphs and level-order tree problems. Depth-first search uses recursion or a stack to plunge down one path before backtracking, which suits path-finding, cycle detection, topological sorting, and exploring connected components. Choosing between them is usually about whether you care about distance or about reaching deep structure.
Binary search variations
Reach for it whenever the search space is sorted or the answer is monotonic — meaning once a candidate works, everything past it works too. Beyond finding an exact value, binary search locates boundaries (first/last occurrence), searches rotated arrays, and 'binary searches on the answer' for problems like 'minimum capacity to ship in D days'. Each step halves the space, turning linear scans into O(log n).
Top-K with heaps
Reach for a heap when you need the k largest, k smallest, or k most frequent elements, or a running median. A heap of size k lets you keep only the best candidates seen so far, pushing and popping in log-k time as you stream through the data. This beats sorting everything (O(n log n)) with an O(n log k) pass, and it naturally handles infinite or streaming input where a full sort is impossible.
Dynamic programming
Reach for DP when a problem has overlapping subproblems and optimal substructure — the answer builds from answers to smaller versions of itself, and those smaller answers repeat. You define a state, write a recurrence relating it to smaller states, and cache results (top-down memoization) or fill a table (bottom-up). It transforms exponential recursion — Fibonacci, edit distance, knapsack, longest common subsequence — into polynomial time by never recomputing a subproblem.
Backtracking
Reach for it when you must enumerate all valid combinations, permutations, or configurations — subsets, N-queens, Sudoku, word search. You build a candidate incrementally and, the moment a partial choice violates a constraint, you abandon that branch and undo the last step. This pruning of dead-end paths is what makes exhaustive search tractable, exploring the decision tree far more efficiently than generating every possibility blindly.
Why patterns beat memorization
There are thousands of coding-interview problems and only so many hours to practice, so grinding them one by one is a losing game. The insight that changes everything is that the vast majority of those problems are surface variations on a small number of underlying patterns. The variable names and the story change, but the machinery — a sliding window, a pair of converging pointers, a recurrence over subproblems — repeats constantly.
Learning to solve by pattern rather than by rote does two things. First, it compresses the space you have to study: master a dozen patterns and you can reason your way through problems you have never seen, because you recognize the shape. Second, it is exactly what interviewers are testing. They rarely care whether you have memorized a specific solution; they want to see you identify the structure of a problem and map it to a known technique out loud. Each pattern below comes with a trigger — a phrase or property in the problem statement that should make you reach for it — because pattern recognition is the real skill.
Scanning arrays: windows and pointers
The most common patterns operate on arrays and strings by avoiding the brute-force nested loop.
The sliding window applies whenever a problem concerns a *contiguous* run — the longest substring without repeats, the smallest subarray summing to at least a target, a maximum over every window of size k. Rather than recomputing each window from scratch (O(n²)), you maintain a window with two boundaries: extend the right edge to add elements and contract the left edge when a constraint is violated, so each element enters and leaves the window at most once, giving O(n).
Two pointers is the sibling pattern for problems where the array is sorted or you need to find a pair or partition. Two indices either converge from opposite ends — as in finding two numbers that sum to a target in a sorted array, where you move the left pointer up to increase the sum or the right pointer down to decrease it — or chase each other in the same direction to remove duplicates in place. The sortedness is what makes each move unambiguous.
Fast & slow pointers specializes this idea for linked lists and cyclic sequences. Advancing one pointer twice as fast as another detects a cycle (they collide inside the loop), finds the middle of a list in a single pass (the slow one is halfway when the fast one reaches the end), and even locates where a cycle begins. It solves in constant space problems that otherwise tempt you into a hash set.
Ranges, trees, and sorted spaces
Three more patterns handle structured data.
Merge intervals is the go-to whenever the input is a collection of ranges — calendar events, booked meeting rooms, overlapping segments on a number line. The universal first step is to sort by start time; this guarantees that any intervals which overlap are now adjacent, so a single pass can merge a running interval with each successor that overlaps it and emit it when the next is disjoint. Recognizing the "ranges" shape and reflexively sorting is most of the battle.
BFS and DFS cover essentially all traversal of trees and graphs. Breadth-first search uses a queue to fan out level by level, which is what you want for shortest paths in an unweighted graph or any "process nodes by distance" question. Depth-first search uses recursion or a stack to dive down one path before backtracking, which suits path enumeration, cycle detection, connected components, and topological sorting. The choice between them usually hinges on whether the problem is about *distance* (BFS) or about *reaching and exploring deep structure* (DFS).
Binary search applies far beyond "find a value in a sorted array". Its true trigger is *monotonicity*: any time the answer space is ordered so that once a candidate works everything larger also works, you can halve the space each step. That unlocks finding the first or last occurrence of a value, searching a rotated sorted array, and "binary searching on the answer" for optimization problems like the minimum ship capacity to deliver packages in D days.
Selection, optimization, and search
The final three patterns tackle harder computational shapes.
Top-K with heaps is the answer whenever you need the k largest, k smallest, or k most frequent elements, or a running median over a stream. A heap of bounded size k lets you retain only the best candidates seen so far, each insertion and removal costing log k, so you process n elements in O(n log k) — better than sorting everything, and it works on streaming or unbounded input where a full sort is impossible.
Dynamic programming is the heavyweight. Its two triggers are overlapping subproblems (the naive recursion solves the same smaller cases repeatedly) and optimal substructure (the best answer is composed of best answers to those smaller cases). You define a state, express a recurrence relating it to smaller states, and either memoize top-down or fill a table bottom-up. This collapses exponential recursion — Fibonacci, coin change, edit distance, knapsack, longest common subsequence — into polynomial time by never solving the same subproblem twice.
Backtracking is for combinatorial enumeration: generate all subsets, permutations, or valid configurations, as in N-queens, Sudoku, or word search on a grid. You build a candidate one choice at a time and, the instant a partial choice breaks a constraint, abandon that branch and undo the last decision. This pruning of doomed paths is what keeps an otherwise exponential search tractable.
Putting the toolbox to work
The way to use these patterns is not to guess randomly but to interrogate the problem for its signals. Is the data a contiguous run? Think window. Is it sorted, or is it asking for a pair? Think two pointers or binary search. Is it a linked list? Consider fast and slow. Ranges? Merge intervals. A graph or tree? BFS or DFS. Do you need the top few of something? A heap. Does the brute-force solution recompute overlapping subproblems? Dynamic programming. Must you enumerate every valid arrangement? Backtracking.
In an interview, narrate this triage aloud. Stating "this looks like a sliding-window problem because we want the longest contiguous substring under a constraint" demonstrates exactly the structured thinking the interviewer is grading, and it usually leads you to a clean, efficient solution instead of a brittle special-case one. The patterns also compose — a problem might use binary search to fix a parameter and then a greedy sweep to check it, or DFS with memoization (which is just top-down DP on a graph). Master the individual patterns and their triggers, and the daunting universe of coding problems shrinks to a manageable, recognizable set of shapes.
Sliding window: contiguous subarray or substring problems where you expand and shrink a window instead of re-scanning.
Two pointers: sorted arrays or pair-finding, converging or same-direction pointers to avoid a nested loop.
Fast & slow pointers: cycle detection and finding the middle of a linked list in one pass.
Merge intervals & binary search: overlapping ranges, and searching any sorted or monotonic answer space in log time.
BFS/DFS: any graph or tree traversal — level-order and shortest hops vs. deep exploration and paths.
Top-K heaps, dynamic programming, and backtracking cover 'k largest', overlapping subproblems, and 'enumerate all valid combinations'.
Quick quiz
A problem asks for the longest substring with at most K distinct characters. Which pattern fits?
What two properties tell you a problem is a dynamic programming candidate?
Algorithms for system design
The handful of algorithms and data structures that keep showing up inside real distributed systems.
The data structures behind databases
Every database is a clever arrangement of a few data structures chosen for how you read and write.
Clean code principles
Code is read far more often than it is written — clean code optimizes for the reader.
Design patterns every developer should know
Named, reusable solutions to problems that keep reappearing in object-oriented design.