{} Coding Interviews · ch.23 · the pattern decision tree
🧩 Part VI · Putting It Together · chapter 23 / 24

Twenty patterns,
one flowchart

Chapters 4–22 handed you the tools; this chapter wires them into a single decision tree you can walk in the first ninety seconds of any interview. Read the problem, harvest the tells, follow the branches — and arrive at a shortlist instead of a blank stare.

You now own about twenty tools. The remaining skill — the one the whole book has been sneaking into your head one 🎯 card at a time — is routing: hearing a problem you've never seen and knowing, in under two minutes, which two or three tools to audition. This chapter is that router, made explicit: one decision tree, one master table of tells, a guide to combo problems, and a drill mode to make the routing a reflex.

Nothing here is new material. Everything here is Chapters 4–22, folded until it fits on a whiteboard.

1Read it twice — the four harvests

Untrained candidates read a problem once, for plot. Trained candidates read it twice: once for plot, once for evidence. On the second pass you're harvesting exactly four things, and each one prunes the pattern space:

  • Input shape. Array? String? Linked list? Tree? Grid? A list of pairs that smells like edges? The input shape alone eliminates most of the map — a linked list will never need a trie, and a course-prerequisites list is a graph no matter what the story says.
  • Target shape. What does the answer look like — a single number, a pair of indices, all possible arrangements, a yes/no, a "minimum k such that"? "All possible" and "minimum k such that" are practically pattern names already (ch. 18 and ch. 9).
  • Magic words. The vocabulary interviewers can't help using: substring, subsequence, sorted, next greater, prerequisites, k most frequent, appears twice except. Section 3 is the full dictionary.
  • Constraint sizes. The 1 ≤ n ≤ 10⁵ line is the interviewer whispering the complexity budget, and the budget eliminates patterns wholesale (ch. 3). Section 5 replays the table.

Four harvests, maybe forty-five seconds. That's the entire input to the flowchart — and conveniently, narrating the harvest out loud is the clarify-and-restate step of the ch. 2 solve loop. Recognition and communication are the same act done audibly.

💡
The tree gives you a shortlist, not a verdict. Landing on "two pointers, maybe hash map" in ninety seconds is a triumph; the brute-force-first step of ch. 2 will disambiguate the finalists. Certainty is not required to start talking.

2Five questions to a shortlist — the decision tree

Here is the whole book as a walkable flowchart. Each question consumes one of your harvests; each answer prunes the map; four or five hops land you on a pattern leaf with its chapter and its tell. Walk it now with a problem you remember — then walk it again with one you don't. The trail of chips it draws is, word for word, the narration an interviewer wants to hear: "the input is an array… the ask is contiguous… sums with negatives… so prefix sums with a hash map."

Interactive · the decision tree Answer the questions; land on a pattern leaf with its why-trail
questions answered
0
pattern leaf
chapter

Notice the tree's economy: the first question (input shape) does more pruning than all the others combined, which is why it's worth reading the input types in the function signature before reading the story. And notice that some leaves are honest about ambiguity — "Dijkstra or binary-search the answer" is a real fork (ch. 17 met it in Swim in Rising Water Hard), and saying the fork out loud scores better than silently picking one.

3The magic words — twenty tells on one page

Every 🎯 card from Chapters 4–22, in one place. This is the reference page of the book — the one to re-read the night before. Read the quoted phrases out loud; you are wiring statement-phrase → pattern-name, and the wiring is auditory.

Part II — linear structures (ch. 4–10)

  • Hash map (ch. 4)“have I seen…?”, “count how many”, “find the pair that…” on unsorted data. The answer to a fifth of all Easies.
  • Two pointers (ch. 5)sorted + pair/triple with a target condition; “in place, O(1) space” → the read/write pointer pair.
  • Sliding window (ch. 6)“longest/shortest substring/subarray that satisfies X”. The word contiguous is the flare; subsequence sends you to ch. 20–21 instead.
  • Prefix sums & intervals (ch. 7)“sum of a range, many queries”; anything with start/end times → sort by start and sweep.
  • Stack / monotonic stack (ch. 8) — nested or matched things → stack; “next greater/smaller to the left/right” → monotonic stack, always O(n).
  • Binary search (ch. 9) — sorted, sure. The deeper tell: “minimize the maximum” / “can you do it with k?” — monotonic feasibility → search the answer.
  • Linked-list pointers (ch. 10)“O(1) space” on a list → two speeds (tortoise & hare); “recently used” → hash map + doubly linked list.

Part III — hierarchies (ch. 11–14)

  • Tree BFS (ch. 11)“level by level / zigzag / view from a side” → floors with a queue.
  • Tree DFS & BST rules (ch. 11–12)“depth / path / subtree property” → DFS; “kth smallest / sorted order” in a BST → in-order; “common ancestor” → compare and walk one way.
  • Trie (ch. 13)“prefix / autocomplete / starts with”, or many words searched on one board.
  • Heap (ch. 14)“kth largest / k closest / k most frequent” → size-k heap; “median of a stream” → two heaps; “merge k sorted” → heap of fronts.

Part IV — graphs & exhaustive search (ch. 15–18)

  • BFS / DFS / flood fill (ch. 15) — a grid where regions or neighbors matter is a graph; “shortest” + unweighted → BFS, no exceptions; “spreads simultaneously” → multi-source BFS.
  • Topological sort (ch. 16)“prerequisites / build order / can you finish”; a cycle means impossible.
  • Union-find (ch. 16)“are these connected / merge accounts / redundant edge” — dynamic connectivity.
  • Dijkstra (ch. 17)“shortest/cheapest” + weighted edges; “at most k stops” → BFS by layers with costs.
  • Backtracking (ch. 18)“all possible / generate every / count the arrangements” + small n (≤ 20). The skeleton never changes; only the choice list and the prune do.

Part V — optimization (ch. 19–22)

  • Greedy (ch. 19)“maximum reach / minimum refuels / can you make it” with a scan-left-to-right feel — then prove it with one exchange-argument sentence, or retreat to DP.
  • DP, 1-D (ch. 20)“how many ways / minimum cost / longest X” with overlapping choices; “subsequence” is DP's word.
  • DP, 2-D & knapsack (ch. 21) — two strings compared → a 2-D table, almost always; “hit exactly this total / split evenly” → subset-sum knapsack.
  • Bits & math (ch. 22)“every element appears twice except…” → XOR; “without extra space” on numbers 0..n → arithmetic or XOR; “rotate/spiral a matrix” → the two memorized moves.
🎯
The tell: magic words outrank everything else in the harvest, because they leak from the solution into the statement. An interviewer who says “subsequence” has already told you the chapter; your only job is to have heard it. When two tells disagree — “sorted” says two pointers, “return indices” says hash map — the tie-breaker is whatever the answer shape needs to survive (sorting destroys indices; ch. 1 met exactly this tie).

4Hunt the tells — training the highlighter

Reading the table is knowledge; spotting tells inside a paragraph of story is skill. The widget below serves real problem statements with the tells buried in plain prose. Click the phrases you think are load-bearing: real tells light up ochre and cast votes for their patterns; decoys cost you a false lead. When you've found them all, the vote tally is your shortlist — exactly the artifact the tree produces, harvested straight from the text this time.

Interactive · the tell-hunter Click the phrases that give the pattern away
problem 1 / 5
tells found
0 / 0
false leads
0
verdict

Two habits worth stealing from this game. First: tells cluster — a statement rarely has just one, and agreement between independent tells ("minimum" + "window" + "every character of") is how you get to high confidence fast. Second: the sentence that constrains the answer ("return the minimum k such that…") is nearly always a tell, while the sentence that sets the story ("Koko loves bananas") never is. Skim the fiction; read the contract.

5Numbers are tells too — constraints as tie-breakers

Chapter 3 built the machinery; here it returns as a router. The constraint line converts to a complexity budget, and the budget eliminates patterns before you've thought at all:

  • n ≤ 20 — an O(2ⁿ) budget. The interviewer is whispering that backtracking (ch. 18) is not just allowed but probably intended.
  • n ≤ ~10³O(n²) is fine: nested loops, 2-D DP tables (ch. 21), the quadratic LIS. Don't burn minutes optimizing what the budget already forgives.
  • n ≈ 10⁵ — you need O(n log n) or better: sort-first patterns, heaps, binary search, and the one-pass family (hash, window, prefix, monotonic stack).
  • n ≈ 10⁹ or more — loops are dead; the answer is O(log n) or O(1): binary search on the answer (ch. 9), fast power, arithmetic, bits (ch. 22).

Constraints are most valuable as tie-breakers between surviving finalists. "Longest increasing subsequence, n ≤ 2500" — subsequence says DP, and n² fitting the budget confirms the simple table is expected, not the clever O(n log n) variant. Same words with n ≤ 10⁵? Now the follow-up is coming, and you can say so before they ask.

🎯
The tell: a suspiciously small n on an otherwise scary problem is a gift, not a typo — n ≤ 12 means "please brute-force this politely" (ch. 18). And a value bound like piles[i] ≤ 10⁹ is a tell about the answer space: too big to scan, monotonic to check — binary-search it (ch. 9).

6Two patterns in a trench coat — combo problems

Mediums that feel hard are usually two Easies standing on each other's shoulders. A combo problem asks two sub-questions, and each sub-question keeps its own tell — so the trick is not a new pattern but a seam: the sentence inside one skeleton that is itself another chapter's tell. The classics:

  • Prefix + hash — Subarray Sum Equals K Medium. Prefix sums (ch. 7) turn subarray sums into subtractions; then the inner question "have I seen P − k before?" is a naked ch. 4 tell. Section 9 walks it end to end.
  • Hash + heap — Top K Frequent Elements Medium. Count with a map (ch. 4); then "which k counts are biggest?" is a ch. 14 sentence.
  • Hash + doubly linked list — LRU Cache Medium. "O(1) lookup and O(1) reorder" — no single structure does both, so ch. 4 and ch. 10 split the job. Chapter 24 makes it the finale.
  • Binary search + greedy — Koko Eating Bananas Medium, Capacity to Ship Packages Medium. Search the answer space (ch. 9); checking one candidate answer — "does speed k finish in time?" — is a greedy left-to-right simulation (ch. 19).
  • Trie + backtracking — Word Search II Hard. The board walk is ch. 18's DFS; the trie (ch. 13) is what lets it refuse doomed branches by prefix.

Spotting the seam in the room is mechanical: route the outer question through the tree first, start writing the skeleton, and when one line of the skeleton turns out to be a question you can't answer in O(1) — route that line through the tree too. The tree is recursive because problems are.

🎯
The tell: two quantities being optimized at once — "the k most frequent", "cheapest within k stops", "O(1) for both operations" — almost always means a combo. Name both halves out loud; interviewers score the decomposition higher than the code.

7When nothing matches — the two usual suspects

Sometimes you walk the tree and every leaf feels wrong. Before concluding you've met problem number twenty-one, know the base rates: an unmatched problem is nearly always a graph in a costume or DP that hasn't admitted it yet.

  • The disguised graph. Ask: what are the states, and what are the legal moves? If both have answers, it's ch. 15–17 wearing a story. Word Ladder Hard never says "graph" — but words are nodes, one-letter edits are edges, and "shortest transformation sequence" is the unweighted-BFS tell from ch. 15. Puzzle scrambles, lock combinations, water-jug states: all graphs.
  • The closeted DP. Ask: is there a choice at each step, and do different choice sequences reach the same smaller problem? If yes, write the brute recursion and memoize it — ch. 20's whole method. This is also where greedy ideas go when the exchange argument won't write itself (ch. 19's coin-change ambush).

And if neither lens bites, fall back to ch. 2's unstick moves, which are pattern-generators in disguise: work a smaller n (often reveals a recurrence — DP), sort it (often reveals two pointers or greedy), hash something (often reveals the O(1) inner question). Every move produces a sentence to say out loud, which means you are never both stuck and silent.

⚠️
The panic trap: deciding the problem needs an algorithm you've never heard of. In a 45-minute interview, it almost never does — that belief is your cue that you skipped a tell, not that the map has a hole. Re-read the statement hunting magic words before you reach for exotica; "I'm re-reading the constraints for what I missed" is a perfectly good thing to say (ch. 24 scripts the whole stuck moment).

8Make it a reflex — drill mode

Recognition has a peculiar property: it's only real at speed. Given thirty seconds, everyone routes correctly; given five, only the trained do — and the interview clock sits in between. So here is the drill this book has been promising since Chapter 1: a 40-problem bank of real titles and constraint lines, a grid of patterns, and a streak counter with no mercy. Play until the per-pattern accuracy stat stops embarrassing you; log misses by pattern, and re-read that pattern's chapter, not the problem's editorial.

Interactive · pattern roulette A real problem appears — name its pattern before your gut cools
0 answered
streak
0
best streak
0
accuracy
weakest pattern

A fair warning about the drill: some problems legitimately accept two answers (Path With Minimum Effort is Dijkstra or binary-search-the-answer; Top K Frequent is heap with a hash under it). The bank scores the chapter that owns the canonical solution, and the why-line names the runner-up when there is one — in the room, naming both is worth more than either.

The pattern, as a whiteboard skeleton — the master tells table in 8 lines:

  1. 1“Substring / subarray” (contiguous) → sliding window; range sums or exact-k counts → prefix (+ hash). “Subsequence” → DP.
  2. 2Sorted + pair/target → two pointers. Unsorted + “have I seen” → hash map.
  3. 3“Next greater/smaller” → monotonic stack; nested/matched → plain stack.
  4. 4“Minimum k such that…” / “minimize the maximum” → binary-search the answer (feasibility is monotonic).
  5. 5Trees: “level by level” → BFS; path/depth/subtree → DFS; BST → in-order; prefixes/many words → trie; “k largest / median” → heap.
  6. 6Graphs: “prerequisites” → topo; “connected/merge” → union-find; shortest unweighted → BFS; weighted → Dijkstra.
  7. 7“All possible…” + n ≤ 20 → backtracking. Scan-and-take-best → greedy only with a one-sentence exchange proof.
  8. 8No match? Ask “states + moves?” (disguised graph) then “overlapping choices?” (closeted DP) — out loud.

9One walk, start to finish — Subarray Sum Equals K

Let's run the whole protocol once, honestly, on Subarray Sum Equals K Medium: given an integer array (negatives allowed) and an integer k, count the subarrays that sum to exactly k. The harvest: input is an array; the ask is a count of contiguous runs; magic word "subarray"; negatives allowed. The tree routes: contiguous → window or prefix; exact sums with negatives kill the window (growing the window can lower the sum, so ch. 6's shrink signal never fires) → prefix sums (ch. 7); and counting all start points fast is a "have I seen this prefix?" question → hash map (ch. 4). A combo, seam and all — the comments below are the walk, verbatim.

🎯
The tell, one last time: "subarray" said contiguous, negatives vetoed the window, and the counting ask demanded a remembered past — three harvests, three prunes, one leaf. That sixty-second walk, spoken aloud, is the highest-scoring minute available in a coding interview.