Author:
Generate a follow-up sub-lesson on any aspect of this topic
Author:
Generate a follow-up sub-lesson on any aspect of this topic
Learn the recurring coding interview patterns, from two pointers to dynamic programming, and the problem cues that tell you which one to reach for. Use it to pick a strategy fast and explain your tradeoffs clearly under time pressure.
Most coding interview problems are variations on about eight ideas. Knowing the coding interview patterns means you read a prompt, spot the cue, and pick a strategy in the first two minutes instead of improvising for twenty. The cues are what matter, so that is how I organize each pattern below.
A pattern is a repeatable strategy tied to a recognizable problem signal. Sorted input suggests binary search or two pointers. A contiguous subarray points to a sliding window. Counting or existence questions hint at hashing.
Under time pressure, pattern recognition saves you from brute force and gives you a vocabulary for explaining your choice to the interviewer.
Two pointers works when the sequence is sorted or has a structure that lets each pointer move in one direction only. Because neither pointer backtracks, you get O(n) instead of the O(n^2) of checking every pair. Pair sum on a sorted array and removing duplicates in place are the classics. Here is pair sum on a sorted array:
Pair sum on a sorted array
A sliding window handles contiguous ranges with a constraint, such as the longest substring without repeats. Expand the right edge, shrink the left when the constraint breaks, and each element enters and leaves at most once. It beats brute force only when shrinking the window restores validity, so negative numbers in a sum problem usually break it. Here is the longest substring without repeats:
Longest substring without repeats
Whenever you rescan an array to answer the same question, ask whether a hash map can answer it in O(1). Two Sum is the standard example. Store each value as you go and check for the complement.
Here is the one-pass version in Python:
Two Sum with a hash map
A prefix sum stores running totals so any range sum becomes prefix[j] - prefix[i]. Combine it with a map from prefix value to count and you can solve subarray-sum-equals-k in one pass, even with negatives where a window fails. Frequency maps drive anagram checks and top-k problems.
Seed the mapInitialize the prefix map with
{0: 1}. Forgetting it misses subarrays that start at index zero.
Index search needs a sorted structure. Answer search needs a monotonic predicate, meaning a yes/no check that flips from false to true exactly once across candidate values. Shipping packages within D days and Koko eating bananas both fit. You search the answer range and test feasibility with a greedy pass. Here is a template that finds the first value where the check passes:
lo, hi = 0, n # search the half-open range [lo, hi)
while lo < hi:
mid = lo + (hi - lo) // 2
if feasible(mid):
hi = mid
else:
lo = mid + 1
# lo is now the first value where feasible() is true
Pick one invariant and hold it. I use a half-open range [lo, hi) with mid = lo + (hi - lo) // 2, and I always write down what is guaranteed about lo and hi. Most boundary bugs come from mixing loop conditions (< versus <=) with the wrong update (mid versus mid + 1), which causes infinite loops.
Choose BFS when you need the shortest path in an unweighted graph or level-by-level output. Choose DFS for path enumeration, subtree computations, and cycle detection. Recursion depth is the DFS risk, so mention an iterative stack if the input can be deep.
Topological sort, through Kahn’s algorithm or DFS finishing order, applies whenever the prompt mentions prerequisites or dependencies. For graphs, mark nodes visited when you enqueue them, not when you dequeue them, or you will push duplicates. Trees need no visited set, but grids and general graphs always do. Here is BFS with the visited check in the right place:
Breadth-first search
Dynamic programming applies when a problem has overlapping subproblems and optimal substructure. Start by defining the state in a sentence, such as dp[i] is the best result using the first i items. The transition then follows from asking what the last decision was.
Two families cover most interviews. Sequence DP (longest increasing subsequence, edit distance) indexes by position in one or two strings. Knapsack DP (coin change, subset sum) indexes by remaining capacity and a choice of items. A 2D table often compresses to 1D when each row depends only on the previous one.
State firstWrite the state definition before any code. A vague state is the usual reason transitions refuse to appear.
Coin change shows the state and transition idea:
Coin change with dynamic programming
Backtracking explores a decision tree by choosing, recursing, and undoing. It fits permutations, subsets, N-Queens, and any constraint satisfaction task where the output size is itself exponential. Subsets show the choose, recurse, undo shape:
Subsets with backtracking
Pruning is what separates a passing answer from a timeout. Sort candidates so you can break early when a sum overshoots, skip duplicates at the same depth, and order branches so the most constrained choice comes first. If the prompt asks only for a count or best value, check for overlapping subproblems, because memoized DP often replaces an exponential search.
Run this before you write code.
n near 10^5 demand O(n log n) or better?State the brute force first, give its complexity, then name the pattern that removes the waste. Say the tradeoff aloud, for example extra O(n) memory for a map in exchange for linear time. The table below lists the typical cost of each pattern.
Next, pick five problems per pattern and practice the cue-to-strategy step before coding. Time yourself on the first two minutes only, since that is where interviews are won.