Skip to content

Pattern Recognition Guide

The single biggest difference between someone who’s “seen a lot of problems” and someone who’s actually fast at interviews and contests is pattern recognition — the ability to read a problem statement and, in seconds, know which of a couple dozen templates it’s really asking for. This page is a reference: a cue-to-pattern table you can scan top to bottom, and a decision tree for when the wording doesn’t immediately ring a bell.

  • A single cue-to-pattern table covering the array/string/linked-list patterns from Phase 5, plus the graph and DP shapes from Phases 6 and 7.
  • A decision tree for working from problem keywords to a pattern when nothing jumps out immediately.
  • Where to go on this site to actually learn each pattern in depth.

Read a problem statement, find the phrase closest to what it’s describing in the left column, and you have your starting point.

Cue in the problemPatternLearn it in
“sorted array, find a pair/triplet summing to X”Two pointersTwo Pointers
“in place, no extra memory” on an arrayTwo pointersTwo Pointers
“longest/shortest contiguous subarray or substring” meeting a conditionSliding windowSliding Window
“linked list has a cycle” / “find the middle node”Fast and slow pointersFast and Slow Pointers
“merge overlapping ranges/meetings/intervals”Merge intervalsMerge Intervals
“array contains numbers from 1 to n” (find missing/duplicate)Cyclic sortCyclic Sort
“reverse a linked list” (whole or in groups of k)In-place reversalIn-place Linked List Reversal
“top / k largest / k closest / kth smallest”Heap (top K)Top K Elements
“merge k sorted lists/arrays”K-way mergeK-way Merge
“generate all subsets/combinations/permutations”BacktrackingSubsets and Combinations
“explore all valid arrangements subject to constraints” (N-Queens, Sudoku)BacktrackingBacktracking
“next greater/smaller element”, “largest rectangle in histogram”Monotonic stackMonotonic Stack
“answer range sum queries fast”, “range update, then query”Prefix sums / difference arrayPrefix Sums and Difference Arrays
“minimize the maximum” / “maximize the minimum” feasible valueBinary search on answerBinary Search on Answer
“fewest steps/moves in an unweighted graph or grid”BFSBreadth First Search
“does a path exist”, “explore every connected component”DFSDepth First Search
“number of ways to reach a target”, “optimal value given a sequence of choices”Dynamic programmingPhase 6: Dynamic Programming
“shortest path with weighted edges”Dijkstra’s algorithmPhase 7: Graphs Advanced
“order tasks respecting dependencies”Topological sortPhase 7: Graphs Advanced
“are these two nodes connected”, “count connected components” incrementallyUnion-FindPhase 7: Graphs Advanced
“frequent range queries and updates on a large array”Segment tree / Fenwick treePhase 8: Segment Trees and Lazy Propagation / Fenwick Tree

When no single phrase jumps out, work top-down through the shape of the input and the shape of the question being asked.

diagram Picking a pattern from problem keywords mermaid

Don’t try to memorize the table — use it as a checklist while practicing. Read a problem, guess the pattern from memory first, then check this page to confirm. Being wrong and correcting yourself here is what builds the instant recall you want to have live in an interview or a contest, where there’s no lookup table to check.

The pattern you pick commits you to a complexity before you write a line. Reading the constraint first and the problem statement second eliminates most of the table above in one step — if n=105n = 10^5, every O(n2)O(n^2) pattern is already wrong, whatever the phrasing suggests.

PatternTimeSpaceLargest n it comfortably handles
Two pointersO(n)O(n) after an O(nlogn)O(n \log n) sortO(1)O(1)10610^6
Sliding windowO(n)O(n)O(k)O(k) for the window’s map10610^6
Fast and slow pointersO(n)O(n)O(1)O(1)10710^7
Prefix sums / difference arrayO(n)O(n) build, O(1)O(1) queryO(n)O(n)10610^6
Monotonic stackO(n)O(n) amortisedO(n)O(n)10610^6
Merge intervalsO(nlogn)O(n \log n) (the sort dominates)O(n)O(n)10510^5-10610^6
Cyclic sortO(n)O(n)O(1)O(1)10610^6
Top K with a heapO(nlogk)O(n \log k)O(k)O(k)10610^6
K-way mergeO(Nlogk)O(N \log k) over N total itemsO(k)O(k)10610^6
Binary search on the answerO(nlogR)O(n \log R), R the value rangeO(1)O(1)10510^5-10610^6
BFS / DFSO(V+E)O(V + E)O(V)O(V)10610^6 nodes
Dijkstra (binary heap)O(ElogV)O(E \log V)O(V)O(V)10510^5-10610^6 edges
Union-FindO(α(n))O(\alpha(n)) per op, effectively O(1)O(1)O(n)O(n)10610^6
Topological sortO(V+E)O(V + E)O(V)O(V)10610^6
Segment tree / FenwickO(logn)O(\log n) per opO(n)O(n)10510^5-10610^6
1D dynamic programmingO(n)O(n) to O(n2)O(n^2)O(n)O(n)10410^4 if quadratic
2D / interval DPO(n2)O(n^2) to O(n3)O(n^3)O(n2)O(n^2)500-5,000
Backtracking (subsets)O(2nn)O(2^n \cdot n)O(n)O(n) depth~20-25
Backtracking (permutations)O(n!n)O(n! \cdot n)O(n)O(n) depth~10-12

Read it backwards to narrow the table. A constraint of n <= 12 is not generosity — it is the problem telling you factorial or subset enumeration is expected, so stop looking for a clever polynomial one. n <= 10^5 with a “count the ways” phrasing rules out O(n2)O(n^2) DP and points at a one-dimensional recurrence or a prefix-sum trick. n <= 500 invites O(n3)O(n^3), which is almost always interval DP or Floyd-Warshall.

Two bounds people misread. Binary search on the answer is O(nlogR)O(n \log R) where R is the range of values, not n — quoting it as O(nlogn)O(n \log n) is wrong and occasionally matters. And a heap solution is O(nlogk)O(n \log k), not O(nlogn)O(n \log n): the whole point of bounding the heap at k is that the log term shrinks, which is why Top K beats sorting when k is small.

Pattern recognition fails in a handful of specific, repeatable ways. All of them are the same mistake — matching on the wording rather than on whether the pattern’s invariant actually holds.

  • Sliding window with negative numbers. “Count subarrays summing to k” reads like a window problem and is not. A window only works when growing it moves the sum monotonically; negatives break that, so shrinking on “too big” can skip valid answers. The real pattern is prefix sums plus a hash map. Check the value range before committing to a window.
  • Two pointers on an unsorted array. The technique depends on knowing which side to move, which depends on order. If sorting is not allowed — because indices must be preserved and the problem returns positions — you need a hash map instead. LC 1 (Two Sum) is the hash-map version; LC 167 is the two-pointer version. Same sentence, different pattern, decided entirely by one word in the constraints.
  • BFS on a weighted graph. “Fewest steps” cues BFS, but BFS is only correct when every edge costs the same. One weighted edge and you need Dijkstra — or, if the weights are only 0 and 1, 0-1 BFS with a deque. The symptom is a plausible wrong answer, never a crash.
  • Greedy where DP is required. “Maximise the total” cues greedy, but greedy is only correct when a local choice can never be regretted. If a later item can make an earlier choice look bad, it is DP. Interviewers ask “can you prove the greedy is optimal?” precisely here, and the honest answer — “I cannot, so let me write the DP” — scores better than a confident wrong greedy.
  • Backtracking when memoisation applies. Enumerating all paths is exponential; if different paths reach the same state, the problem is DP wearing a backtracking costume. The tell is a count or an optimum in the question rather than the arrangements themselves.
  • Matching the noun instead of the question. “Tree” does not mean tree DP, “graph” does not mean Dijkstra, and “string” does not mean KMP. The data structure narrows the field; the question being asked about it picks the pattern.
  • Committing before reading the constraints. The single highest-yield habit on this page is to read the constraint block first. It rules out more patterns in five seconds than the statement does in five minutes.

The cue-to-pattern table above, as problems. Read each title and constraint set, commit to a pattern out loud, and only then open it — the point of this ladder is the guess, not the solution.

71 problems
12 easy48 medium11 hard

Work down the ladder. Tick each problem off as you go — progress is saved in this browser, and the Export button in the filter bar writes it to a file you can keep.

They askWhat they’re checkingThe answer
“What made you pick that pattern?”Whether recognition is reasoned or memorisedName the cue and the invariant: “the window’s sum is monotonic because all values are positive, so shrinking on too-big never skips an answer.” A cue alone sounds like pattern-matching; the invariant shows you checked
“The values can now be negative. Does your approach still work?”Whether you know your own assumptionNo — the window invariant breaks. Switch to prefix sums plus a hash map, O(n)O(n) time and O(n)O(n) space instead of O(1)O(1). This is the most common single follow-up in the whole set
“Could you do it without sorting?”Two pointers versus hashingSorting destroys original indices. If the answer is a pair of positions, a hash map is the right structure; if it is a pair of values or the array is already sorted, two pointers wins on space
“Why a heap rather than sorting?”Precision about kO(nlogk)O(n \log k) against O(nlogn)O(n \log n), and O(k)O(k) space against O(n)O(n). When k is small and n is huge — a stream, or a top-10 over millions — the difference is real. When k is close to n, just sort
“Some edges now have weight 2. What changes?”BFS’s preconditionBFS is only shortest-path-correct on uniform edge costs. Switch to Dijkstra, O(ElogV)O(E \log V). If the weights are only 0 and 1, 0-1 BFS with a deque keeps it linear
“Prove your greedy is optimal”The line between greedy and DPExchange argument — show any optimal solution can be transformed into the greedy one without getting worse. If you cannot construct it, say so and write the DP; a greedy you cannot justify is a coin flip
“This looks like backtracking, but n is 10^5”Reading the constraint as a hintExponential is off the table, so the problem wants a count or an optimum rather than the arrangements themselves — that is DP or a greedy, and the constraint said so before the statement did
“You matched two patterns. Which and why?”Handling compositionSay both and how they compose: “k closest points” is a distance computation feeding a size-k heap. Most medium-and-up problems are two cues stacked, and naming the seam is the answer
“What if the input does not fit in memory?”Whether the pattern survives streamingAnything O(1)O(1)-space and single-pass survives: fast/slow pointers, a bounded heap, a rolling hash. Anything needing random access or a full sort does not — that becomes an external merge
pch.quizTag pch.quizDefaultTitle
  1. "Count the subarrays whose sum equals k." The array can contain negative numbers. Which pattern?

    pch.quizShowAnswer

    B — Prefix sums plus a hash map of counts — A sliding window needs the sum to move monotonically as the window grows -- true only when all values are non-negative. With negatives, shrinking on "too big" can skip valid answers. The prefix-sum-plus-hash-map version is O(n) and indifferent to sign. This is the single most common mis-match in the whole table, because the wording is pure window.

  2. The constraint says `n <= 12`. What is the problem telling you?

    pch.quizShowAnswer

    B — That exponential or factorial work is expected -- subsets or permutations — A bound that tiny is never generosity. 12! is about 479 million and 2^12 is 4096, so the setter has sized the input for full enumeration. Reading the constraint block before the statement rules out more patterns in five seconds than the statement does in five minutes.

  3. "Fewest moves from A to B" in a graph where some edges cost 2 and some cost 1. Is BFS correct?

    pch.quizShowAnswer

    B — No -- BFS is shortest-path-correct only on uniform edge costs; use Dijkstra — BFS relies on discovering nodes in non-decreasing distance order, which holds only when every edge adds the same amount. One heavier edge and a node can be reached first by a cheap-hop-count path that is actually more expensive. The failure mode is a plausible wrong number, never a crash. Weights of only 0 and 1 are the special case: 0-1 BFS with a deque keeps it linear.

  4. Two Sum on a sorted array versus Two Sum on an unsorted array returning indices. Same pattern?

    pch.quizShowAnswer

    B — No -- sorting destroys the original indices, so the unsorted version needs a hash map — Sorting pairs does technically work and is a fine thing to mention, but it costs O(n log n) where the hash map is O(n), and it is more code under time pressure. The deeper point is that one word in the constraints -- sorted or not, indices or values -- flips the pattern for an identical-sounding sentence. LC 167 is two pointers; LC 1 is a hash map.

  5. You want the k largest of n elements. Why prefer a heap over sorting?

    pch.quizShowAnswer

    B — O(n log k) time and O(k) space instead of O(n log n) and O(n) -- which matters when k is small or the input is a stream — Bounding the heap at k is what shrinks the log term, and O(k) space is what lets it run over a stream that never fits in memory. When k approaches n the advantage disappears -- just sort. Note a heap does *not* hand back sorted output for free; you pay another k log k to drain it.

  6. A problem says "maximise the total value" and a greedy choice looks obviously right. What should you do before writing it?

    pch.quizShowAnswer

    B — Try to construct an exchange argument; if you cannot, write the DP instead — Greedy is correct only when a local choice can never be regretted, and the proof obligation is the exchange argument: any optimal solution can be transformed into the greedy one without getting worse. Interviewers ask "prove it" exactly here. "I cannot prove it, so let me write the DP" scores better than a confident wrong greedy -- and passing the samples proves nothing, since the samples are chosen to be easy.

  7. "Find the k closest points to the origin." How many patterns is that?

    pch.quizShowAnswer

    B — Two, composed: a distance computation feeding a size-k heap — Cues stack, and naming the seam is the answer. The distance is the key function; the heap is the selection structure. Most medium-and-up problems are two cues composed rather than one cue matched. Quickselect is a genuine alternative for the selection half -- O(n) average instead of O(n log k) -- and mentioning the trade is a bonus, not a replacement for seeing the composition.

  • Read the constraint block before the problem statement. It eliminates more patterns in five seconds than the prose does in five minutes. n <= 12 means enumerate; n <= 500 invites O(n3)O(n^3); n <= 10^5 forbids O(n2)O(n^2).
  • Match the question, not the noun. “Tree” is not tree DP, “graph” is not Dijkstra, “string” is not KMP. The structure narrows; the question decides.
  • Name the invariant, not just the cue. “Sliding window because the sum is monotonic, and it is monotonic because all values are positive” is a reasoned answer; “sliding window because it says substring” is a guess.
  • The four classic mis-matches: window with negatives (use prefix sums + hash map) · two pointers without sort order (use a hash map) · BFS on weighted edges (use Dijkstra, or 0-1 BFS) · greedy without an exchange argument (use DP).
  • Cues stack. Most medium-and-up problems are two patterns composed; find the seam.
  • Use this page as a checklist, not a lookup. Guess from memory first, then check. Being wrong here is what builds recall for when there is no table to check.
  • Match phrases in the problem statement to the cue-to-pattern table first — most problems are a direct hit or a close combination of two rows.
  • When nothing jumps out, walk the decision tree from the shape of the input (array, linked list, graph, “choices”) down to a specific pattern.
  • Watch for cues that look alike but diverge under extra constraints (negative numbers, non-monotonic windows) — confirm the invariant before committing.
  • Every pattern named here has its own deep-dive page earlier in this site; this page is the index, not the tutorial.

Next: Contest Strategy — how constraints, time limits, and problem ordering change the way you apply these same patterns under contest pressure.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading