Skip to content

Lesson 11 of 27From idea to plan

The Pattern Map

Walk any problem from input type, through wording and constraints, to a short list of patterns worth trying.

15 min read0/7 questions

You now have four separate signals: the shape of the input, the phrases in the wording, the constraints, and the shape of the output. On their own each one narrows things a little. Together they usually leave one or two candidate patterns. This lesson puts them on one map, so that when you meet a new problem you follow a route instead of guessing. It is the pattern cheat sheet from How to Solve Problems, turned into a route.

The map is a starting point, not a law. Its job is to give you a first pattern to try in under a minute, and a backup if the first one breaks.

The map

Read it left to right: what you are given, what the wording says, what the constraints allow, and the pattern that results. The last column is the fallback when a constraint or detail rules out the first choice. Press play to follow three real problems through it.

From problem to pattern
InputWordingConstraintsPatternFallbackProblem: read twiceProblemread twiceArray / stringArray / stringSorted arraySorted arrayGrid / edgesGrid / edgesTreeTreeItems to chooseItems to choosecontiguous: substring, subarraycontiguoussubstring, subarraypair, find x: search, k-thpair, find xsearch, k-thfewest steps: spread, reachfewest stepsspread, reachdepth, path: subtree answerdepth, pathsubtree answerall / ways: subsets, ordersall / wayssubsets, ordersn ≤ 10^5: values ≥ 0?n ≤ 10^5values ≥ 0?O(log n) asked: or n up to 10^9O(log n) askedor n up to 10^9equal costs: m · n ≤ 10^5equal costsm · n ≤ 10^5n ≤ 10^4 nodes: height ok?n ≤ 10^4 nodesheight ok?n ≤ 20: list them alln ≤ 20list them allSliding windowSliding windowBinary searchBinary searchBFSBFSDFS recursionDFS recursionBacktrackingBacktrackingPrefix sums + mapPrefix sums + mapTwo pointersTwo pointersDijkstraDijkstraBFS by levelBFS by levelDynamic programmingDynamic programmingyesyesyesyesyesnegativespair sumweightedper levelcount only

Longest Substring Without Repeating Characters: a string, *substring* means contiguous, n up to 5 · 10^4 and the rule only gets worse as the window grows. Sliding window.

1/4

The same map as a table

The diagram shows the five most common routes. Here are more, grouped by what you are given.

GivenWording / goalConstraint or detailTry firstFallback
Array / stringcontiguous, longest / shortest rangevalues non-negativeSliding windowPrefix sums + hash map
Array / stringseen before, frequency, anagramanyHash map / setSort, or a 26-slot array
Arraynext greater / smallern up to 10^5Monotonic stack
Sorted arrayfind value, first / last positionO(log n)Binary search
Sorted arraypair / triple with a sumO(1) spaceTwo pointersHash map if unsorted
Anything monotonesmallest x such that it worksanswer range up to 10^9Binary search on the answer
Grid / edgesislands, regions, connectedanyDFS or BFSUnion-find
Grid / edgesfewest stepsequal costsBFSDijkstra if weighted
Edges with directionorder, prerequisitesanyTopological sortDFS cycle check
Treeheight, path, subtree propertyanyDFS recursionIterative DFS if very deep
Treeper level, left / right viewanyBFS by level
Itemsall subsets / orders / placementsn ≤ 20Backtracking
Items or a numbercount ways, min cost, can reachn up to 10^4Dynamic programmingGreedy if a local rule is provably safe
Valuestop k, k-th, running mediank much smaller than nHeapQuickselect, sorting
Intervalsmerge, overlap, roomsanySort by start, sweepMin-heap of end times
Numbersappears once, without extra spaceO(1) spaceXOR, bit tricks

Drill each region of the map

Match the pairs0/4 matched

Arrays and strings: match the problem to its first pattern.

Choose an item, then its match on the other side.
Match the pairs0/5 matched

Grids, graphs, and trees: match the problem to its first pattern.

Choose an item, then its match on the other side.
Match the pairs0/4 matched

Choices and counting: match the problem to its first pattern.

Choose an item, then its match on the other side.
Match the pairs0/4 matched

Heaps, intervals, and bits: match the problem to its first pattern.

Choose an item, then its match on the other side.

When the map gives two answers

Often a problem matches two routes. "Pair that sums to target" is two pointers if sorted and a hash map if not. "Longest increasing" is DP if it is a subsequence and a window if it is a subarray. When that happens, go back to the detail that separates them and check it in the prompt, or ask the interviewer.

Quick check
'Given an array of positive integers, find the length of the shortest contiguous subarray whose sum is at least target.' The map gives sliding window and prefix sums. Which detail decides?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the route through the map in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

Rotting Oranges

A crate is a grid where 0 is an empty slot, 1 is a fresh orange and 2 is a rotten one. Every minute, each rotten orange rots the fresh oranges directly above, below, left and right of it. Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never be reached.

[[2, 1, 1],
 [1, 1, 0],
 [0, 1, 1]]   →  4
 
[[2, 1, 1],
 [0, 1, 1],
 [1, 0, 1]]   →  -1   (bottom-left orange is cut off)
 
[[0, 2]]      →  0    (nothing fresh to begin with)

Constraints

  • 1 <= grid.length, grid[i].length <= 10
  • grid[i][j] is 0, 1 or 2
def oranges_rotting(grid: list[list[int]]) -> int: # Start a BFS from every rotten orange at once and count the layers. pass
Key terms
pattern map
A route from input shape, through wording and constraints, to a first pattern and a fallback.
fallback pattern
The second choice when a detail (negatives, weights, count only) breaks the first one.
binary search on the answer
When 'can it be done with x?' is yes for every x past some boundary, binary search for that boundary.
multi-source BFS
BFS that starts from many cells at once, so levels measure the time for all of them to spread.
topological sort
An order of a directed graph's nodes where every edge points forward. Exists only if there is no cycle.