Free lessons · from Think in Patterns

Which pattern is this?

Problems rarely say which pattern they want. The statement gives cues: the shape of the input, the word used for the answer, a constraint that rules out the obvious approach. Match the cue, turn to the chapter, and start from its template.

By what the problem asks for

Read the problem twice and underline the words. They usually name the pattern for you.

You read…ThinkChapter
“two numbers that…”, “does a duplicate exist”, “count how often”, “group the…”hash map or set1 Arrays & Hashing
“sum of a range”, “subarray with sum k”, “equal zeros and ones”prefix sums2 Prefix Sum
numbers in 1..n, “missing”, “duplicate”, “first missing positive”, O(1) spacecyclic sort3 Cyclic Sort
rotate, spiral, set rows and columnsmatrix walks4 Matrix & Grid
palindromes, find a pattern in text, parse a stringexpand around centre, KMP5 Strings
sorted array, pair or triplet, “in place”, “remove”, “move zeroes”two pointers6 Two Pointers
“longest / shortest substring or subarray with…”, “at most k distinct”, window of size ksliding window7 Sliding Window
sorted input, “find the position”, “minimum capacity / speed / days such that…”binary search, binary search on the answer8 Binary Search
“kth largest”, custom order, values in a small rangequickselect, custom sort, counting sort9 Sorting & Quickselect
reverse, merge, reorder, remove the nth from the endlinked list with a dummy head10 Linked List
cycle, middle, “without extra space” on a list, repeated function applicationfast and slow pointers11 Fast & Slow Pointers
brackets, “undo”, nested structure, evaluate an expressionstack12 Stack
“next greater / smaller”, “days until warmer”, largest rectangle, window maximummonotonic stack or deque13 Monotonic Stack
depth, path sum, diameter, lowest common ancestor, serialisetree DFS14 Binary Trees
“level by level”, right side view, zigzag, connect siblingstree BFS14 Binary Trees
BST property, kth smallest in a BST, validate, insert, deleteinorder is sorted15 Binary Search Trees
“starts with”, prefix search, many words to match against a texttrie16 Tries
“top k”, “k closest”, “k most frequent”, stream of numbersheap of size k17 Heaps
running median, two halves of a streamtwo heaps17 Heaps
“merge k sorted…”, “smallest range covering…”k-way merge17 Heaps
islands, regions, “reachable”, clone a graph, shortest steps in a gridgraph BFS / DFS18 Graph BFS & DFS
prerequisites, ordering with dependencies, “is it possible to finish”topological sort19 Topological Sort
connected components, “redundant connection”, merge accounts, equality constraintsunion-find20 Union-Find
weighted edges, “cheapest”, “minimum effort”, “within k stops”, connect all pointsDijkstra, Bellman-Ford, Prim, Kruskal21 Shortest Paths & MST
“all subsets / permutations / combinations”, “generate every”, N-Queens, Sudoku, word searchbacktracking22 Backtracking
“number of ways”, “minimum cost to reach”, “longest increasing”, choices along a line1-D DP23 1-D Dynamic Programming
two strings, a grid of paths, edit distance, subsequence of two sequences2-D DP24 2-D Dynamic Programming
“can we pick items to reach a sum”, “coins”, “partition into equal halves”, “burst / cut / merge”knapsack, interval DP25 Knapsack & Interval DP
intervals: merge, insert, overlap, rooms, arrowssort by start or end26 Intervals
“minimum number of jumps / refuels / changes”, a local choice that is safegreedy27 Greedy
“without using +”, “appears once”, powers of two, count set bitsbit manipulation28 Bit Manipulation
pow, sqrt, primes, digits, points on a line, overflowmath29 Math & Geometry
“design a… with O(1) get and put”, LRU, LFU, random access, time-based storedata-structure design30 Data-Structure Design

By the constraint

The input size tells you the complexity the interviewer expects. A Python solution does roughly 10⁷ simple operations a second, so the limits below are for Python; in C++ or Java each row stretches about ten times further.

n is aboutExpected timePatterns that fit
≤ 20O(2ⁿ) or O(n!)backtracking, bitmask over subsets
≤ 200O(n³)interval DP, Floyd–Warshall
≤ 3 000O(n²)2-D DP, brute-force pairs, expand around centre
≤ 10⁵ or 10⁶O(n log n) or O(n)sorting, heaps, binary search, hashing, two pointers, sliding window, prefix sums, monotonic stack
≤ 10⁹ or moreO(log n) or O(1)binary search on the answer, math, bit tricks

Two cues that override everything

  • “Contiguous” (subarray, substring) → sliding window or prefix sums. “Not necessarily contiguous” (subsequence) → DP or greedy.
  • “Sorted” in the input → two pointers or binary search before anything else. If it is not sorted and the answer does not need the original order, ask whether you may sort it.

When two patterns fit

Prefer the one with the better complexity for the constraint, then the one with less code. Say both to the interviewer: “This could be a heap or quickselect; quickselect is O(n) average, the heap is O(n log k) but simpler. Which would you like?”

This is page 107 of Think in Patterns. Each of these 30 patterns has its own chapter, with a template, worked problems and exercises, and the six AI-era chapters have a cue table of their own.