Card 07/ 07

RecapDifficulty: Advanced2 min

Recap: Choosing a Pattern

Structure first, then the question's shape, then what the values allow: each pattern is chosen by a property, never by a word.

A pattern is chosen by testing the problem for properties in a fixed order: the structure of the input, then the shape of the question, then what the values allow. A word in the statement is a hint to test for a property, never the property itself. Each pattern, its cue written as a property, and the alternative it is most often confused with:

Each pattern's cue as a property, and its nearest alternative
PatternCue as a propertyNearest alternativeWhy not
Fast and slow pointersA linked list; a loop, the middle, or a position from the endA hash set of nodes seenIt costs O(n) memory
Linked list reversalA linked list reordered without a copyCopying into an arrayIt costs O(n) memory
Tree patternsA tree; the answer comes from above, below or the levelCopying the tree into a listIt loses the parent and child links
Grid traversalA map of cells; movement between cells that touchBuilding a graph firstThe grid already gives the neighbours
Graph modellingLinks in pairs that nobody drewA search of the listIt cannot follow links
IntervalsItems with a start and an end; overlaps or gapsOne slot per time unitIts size follows the range, not the items
Heap patternsThe k best from anywhere, or a running middleSorting everythingIt needs every item first, O(n log n)
Modified binary searchA yes-or-no test that changes onceChecking every candidateIt is O(n) tests
Monotonic stackFor each item, the nearest larger or smaller on one sideScanning from each itemIt is O(n²)
Sliding windowA contiguous run; fixed length, or a condition that moves one wayHeap patternsA heap takes items that need not touch
Prefix sumsRange sums with negative values, or many questions of fixed dataSliding windowNegative values break the window
Two pointersSorted input; pairs or a splitBinary search per elementIt is O(n log n) and answers a single point
Bit manipulationSmall sets of flags, or constant memory for a single valueHash map patternsA map costs O(n) memory
Hash map patternsSingle items in unsorted input; memory allowedEvery pairIt is O(n²)

Test structure first because it rules out the most patterns, and when no property fits, write the brute force and cost it: the step that dominates usually names the pattern that removes its waste.