Lesson 1 of 5
Recognizing the pattern
A new interview problem is usually a pattern you know in a new costume. Read what the input is, what the question asks and how big the input can get, and those signals point to the walk, the notebook and the cost.
Name the pattern a problem points to from the signals in its statement
Explain why a signal fits its pattern by saying what the notebook must remember
Ask the questions in a fixed order to narrow thirty patterns to one or two
Turn a size limit into the complexity a solution needs
Check a candidate pattern's promise against the fine print before building on it
A warehouse counts the packages that arrive each hour: [3, 1, 4, 2, 5]. For each hour, report how many hours pass until a busier hour, or 0 if no busier hour comes.
You have probably never seen this problem. You have seen its structure. Rename hours to days and packages to temperatures, and it is Daily Temperatures (LeetCode 739), which module 5 solves with a monotonic stack.
Interview problems come in costumes. The research digest notes that verbatim repeats of known questions are declining and that interviewers deform problems: the structure stays, while the story, the names or one rule change. A memorized solution does not survive that; reading does. This lesson teaches the reading: three things to look for in any statement (the input, what it asks, and how big it can get), the signals that point to each pattern, and how to check a guess before you build on it.
A signal names the notebook
What tells you the warehouse problem needs a stack? Not the input: two sum, top k and most window problems take a list too. The words of the question do. A signal is a phrase in a problem statement that says what the notebook (the values the code keeps up to date as it walks) has to remember. Here it is "for each hour, the next busier hour".
Follow it. As we walk the hours left to right, some hours have not met a busier hour yet; call them waiting. A new hour ends the wait of every waiting hour it beats. The waiting hours never get busier from oldest to newest: if a newer waiting hour were busier than an older one, it would have ended the older one's wait when it arrived.
So a new hour checks the newest waiting hour first. If it does not beat the newest, it cannot beat any older one, since each older one is at least as busy, and it stops there. Newest first is a stack: a list we add to and remove from only at its end, the top. A stack kept in order like this (counts never rising from bottom to top, or never falling when we want the next smaller item) is the monotonic stack of module 5.
So the signal hands us the notebook before we write a line. The trace runs it on the warehouse counts. waiting is drawn standing up with its top at the top, and it holds hour numbers, not package counts: hour 0 stands for its 3 packages. waiting[-1] reads the top (the last item of the list), and waiting.pop() removes the top and hands it back. wait holds the answers, and the arrows hour and earlier sit under counts.
Before you step through, guess two things: the answer for hour 0, and which hours are still waiting when the walk ends.
def hours_until_busier(counts):wait = [0] * len(counts)waiting = []for hour in range(len(counts)):while waiting and counts[hour] > counts[waiting[-1]]:earlier = waiting.pop()wait[earlier] = hour - earlierwaiting.append(hour)return wait
(nothing printed yet)That is the move this lesson trains: phrase, then notebook, then a frame you already know. The code was never the hard part. Hearing "the next busier hour" as "a stack of hours still waiting" was.
Costumes hide traps in the small words. "Busier" means strictly more packages, so a tie does not end a wait. Predict this one.
This is the function from the trace, run on a list that starts with a tie. "Busier" means strictly more packages. Type exactly what it prints.
def hours_until_busier(counts):
wait = [0] * len(counts)
waiting = []
for hour in range(len(counts)):
while waiting and counts[hour] > counts[waiting[-1]]:
earlier = waiting.pop()
wait[earlier] = hour - earlier
waiting.append(hour)
return wait
print(hours_until_busier([4, 4, 1, 6]))
Now change the costume yourself. The next exercise asks about prices and the next cheaper day. Same signal, flipped: the next smaller item instead of the next bigger one.
A list gives one price per day. Write days_until_cheaper(prices), which returns, for each day, how many days pass until a strictly lower price, or 0 if no lower price comes. Name the signal before you type: it is the warehouse problem with the comparison flipped. The last test has 30,001 days, so a loop that scans ahead from every day will be too slow. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.Twelve signals
Which phrases point where? Twelve signals point to the main patterns of this course. Each points to its pattern because it says what the notebook must remember, so read the last column as the reason.
| Signal in the problem | Pattern | What the notebook must remember |
|---|---|---|
| The input is sorted | Binary search, or two pointers | lo and hi around the part still in play, or left and right moving inward |
| A contiguous subarray or substring (an unbroken run of neighbors) | Sliding window, or prefix sums | What is inside the window, or the running totals seen so far |
| A pair that adds up to a target (each item's complement, the target minus the item), a repeat | Seen-before hash map | The items already passed, in a dict or a set |
| The next greater (or smaller) item for each item | Monotonic stack | The items still waiting for their answer |
| The top k, the k most frequent, the kth largest | Heap of size k | The k best so far, with the weakest of them on top |
| The fewest steps, moves or minutes | Breadth-first search | A queue in order of distance, and a visited set |
| Islands, regions, connected groups | Depth-first search, or union-find | A visited set, or a parent for each item |
| Dependencies, prerequisites, an order of tasks | Topological sort | Each task's count of unmet prerequisites, and a queue of ready tasks |
| All combinations, subsets, orderings or arrangements | Backtracking | The choices made so far |
| The number of ways, or the most or fewest of something (like the lowest cost), with choices that overlap | Dynamic programming | A table of answers to smaller questions |
| Intervals, meetings, start and end times | Sort by start, then sweep | The last merged interval, or the rooms in use |
| Words that start with a prefix, autocomplete | Trie (prefix tree) | A tree of letters with word ends marked |
"Choices that overlap" in the dynamic programming row means the same smaller question comes up again and again. When you count the ways to climb a staircase, every path that steps on stair 5 asks the same question: how many ways lead from stair 5 to the top?
The input narrows the field; the question decides. A list can lead to a hash map, a window, a stack, a heap or dynamic programming. What it asks ("a pair", "a stretch", "the next bigger", "the top k", "the number of ways") picks among them. Some signals point two ways: "contiguous" to a window or prefix sums, "connected regions" to depth-first search or union-find. The last section shows how the fine print chooses.
Try two problems written in costume.
A grid holds empty cells, fresh fruit and rotten fruit. Each minute, every rotten fruit spoils the fresh fruit directly above, below, left and right of it. Return the number of minutes until no fresh fruit is left, or -1 if some fruit never spoils. Which pattern fits?
Choose one answer, then check.
A string of digits can be read as letters, with 1 as A up to 26 as Z. "1226" has five readings: 1 2 2 6, 12 2 6, 1 22 6, 1 2 26 and 12 26. The problem asks how many readings a string has, for strings of up to 100 digits. Which pattern fits?
Choose one answer, then check.
Recognition is built by mixing. Module 0 named the two ways to arrange practice: blocked (one pattern at a time) and mixed, also called interleaved (patterns shuffled in one set, so each problem starts with "which pattern is this?"). Mixed practice beat blocked practice on delayed tests (Rohrer and Taylor, 2007), and this lab mixes once each pattern has been seen. The set below draws one-line problems at random from across the course. Get five right in a row to complete it, and come back to it between other lessons.
One-line problems from across the course, in random order. Pick the pattern that fits; five right in a row completes the set.
Which pattern fits this problem best?
Decide whether the edges connect every computer into one network, adding cables one at a time.
Asking the questions in order
The table has twelve rows, but this course has taught about thirty patterns. Where do you start? Ask the same few questions in the same order, and let each answer cross patterns off. First: what is the input? Then, for a list or a string: does it want every combination? Is the answer a contiguous stretch? Is the list sorted? Only then: what exactly does it ask for?
The input comes first because one answer clears whole modules. A grid or a graph leaves 6 of the 30 patterns; a tree leaves 3. The pattern picker below asks exactly these questions. Its board shows the 30 patterns it knows as chips, and each answer strikes out the ones that cannot fit. Answer it for the warehouse problem.
"What does it ask for?" ends with "None of these", which suggests a brute force (the plain, slower approach that tries every possibility) or sorting first. That is a plan, not a failure. Write the slow version you trust, say its cost, then look for the work it repeats. In Google's format, a brute force first (10 to 15 minutes) and then the optimized version is reported as standard. Lesson 5 of this module turns that into a method for hard problems.
The size limit sets the budget
Two patterns can both fit the words and still differ in speed by a factor of thousands. The size limit says which one the problem wants. Module 2's rule of thumb: Python does roughly 107 (10 million) simple steps per second, so a solution fits a one second budget when its step count at the largest n is about 107 or less.
Here is that rule turned around: each row gives the most expensive class that still fits at that size.
| Largest n | Steps at that n | Most expensive class that fits | Patterns that live there |
|---|---|---|---|
| about 10 | 10 × 9 × ... × 1 = 3,628,800 (written 10!, "10 factorial") | O(n!), every ordering | Backtracking over orderings |
| about 20 | 220 = 1,048,576 | O(2n), every subset | Backtracking over subsets |
| about 1,000 | 1,0002 = 1,000,000 | O(n2), every pair | A loop inside a loop, a table of n by n cells |
| 104 to 105 | about 1.7 million for n log n at 105 | O(n log n), a sort and a pass | Sort first, heaps, binary search, intervals, and everything faster |
| 106 or more | 1,000,000 for n at 106 | O(n), one pass | Hash maps, windows, stacks, prefix sums |
A size limit is a signal too. n ≤ 20 on a list problem is a strong hint that the intended solution tries every subset. n up to 105 says the loop over every pair is the brute force you name and then beat: 105 × (105 − 1) / 2 is about 5 × 109 pairs, over 8 minutes at 107 steps a second. A huge range of possible answers with a yes-or-no check, like an eating speed between 1 and 109, points to binary search on the answer: 30 halvings cover a billion values, since 230 = 1,073,741,824.
To recap: read the limit, find the most expensive class that fits, and cross off every pattern slower than that.
A problem allows up to 2 × 105 numbers. Your first idea compares every number with every other number: about n2 steps. At about 107 simple steps per second, how many seconds does that take at the largest n? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
That completes the three reads: the input, what it asks, and the size. Reading a problem is a walk with a notebook of its own:
Try all three reads on paper, on a problem from data work.
Read this problem on paper before you open the steps, once for the input, once for what it asks, and once for the size limits:
A pipeline has up to 104 jobs and up to 5 × 104 rules. A rule (a, b) means job a must finish before job b starts. Return an order that runs every job after all the jobs it depends on, or an empty list if no such order exists.
Name the pattern and its cost, then open the steps one at a time.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
When two patterns fit, check the promise
Some signals point two ways, and the picker sometimes hands you two cards. Each candidate's promise (the sentence about its notebook that stays true after every step) holds only under certain conditions, and the fine print of the statement says whether they hold.
Take a pair that adds up to a target. Two pointers from both ends answer it on a sorted list with O(1) extra space. Their promise: no pair that uses an item outside left to right adds up to the target. When the sum is too small, the code drops nums[left], which is safe only because in a sorted list nums[right] is the biggest partner left. Here is that code, run on a list that is not sorted. Before you step through, find the two pairs in [1, 4, 2, 3] that add up to 5, and guess whether the pointers find either one.
def pair_from_ends(nums, target):left = 0right = len(nums) - 1while left < right:pair_sum = nums[left] + nums[right]if pair_sum == target:return [left, right]if pair_sum < target:left += 1else:right -= 1return []
(nothing printed yet)Nothing in the code is wrong. The promise does not hold for this input. Sorting first would find 1 + 4 on the first check, at positions 0 and 3 of [1, 2, 3, 4]. But if the problem wants positions in the original list, those are positions in a copy: the 4 started at position 1. Sorted or not, and positions or not, decide between two pointers and a hash map.
Every signal that points two ways has a question like this behind it:
| Candidates | Fine print to check | Why it decides |
|---|---|---|
| Two pointers or a hash map, for a pair | Is the list sorted? Are positions wanted? | Dropping an end is safe only in sorted order, and sorting moves the positions |
| Sliding window or prefix sums, for a stretch with a sum | Can numbers be negative? | The window stops shrinking once the sum falls short, which is safe only if dropping a number never raises the sum (module 4 broke it with [1, -2, 5]) |
| Depth-first search or union-find, for connected groups | Is the whole graph given at once, or do edges arrive one at a time? | A search answers once for a fixed graph; union-find merges two groups per new edge, so it can answer again after every edge without searching from scratch |
| Breadth-first search or Dijkstra's algorithm (module 10's weighted shortest paths), for the cheapest route | Does every step cost the same? | Reached first means cheapest only when every step costs the same |
| Dynamic programming or backtracking | Count the ways, or list them all? | A count reuses answers to smaller questions; a list has to build every answer |
| Greedy or dynamic programming, for the most or fewest | Is the best move now always safe? | Greedy never undoes a choice: coins 1, 3 and 4 for an amount of 6 give 4 + 1 + 1, three coins, when 3 + 3 needs two |
Every row is a clarifying question. "Is the input sorted?", "Can values be negative?" and "Do I return positions or values?" are the questions to ask before you plan, and their answers pick the pattern.
Order totals arrive in a list, not sorted, up to 105 of them. Given a target, return the positions of two orders whose totals add up to the target. Which plan fits?
Choose one answer, then check.
When positions are wanted and the list is not sorted, the seen-before dict is the tool. Put it together.
Put the lines in order to build pair_positions(nums, target), which returns the positions of two different items that add up to target, or [] if there are none. Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
for i, x in enumerate(nums):if x in seen:nums.sort()return []if target - x in seen:seen[x] = iseen = {}def pair_positions(nums, target):return [seen[target - x], i]
The second row of the table works the same way: "a stretch with a sum" points two ways, and one word in the statement decides. Find it in this costume.
A battery logs the change in its charge each minute: positive while it charges, negative while it drains. Count the runs of consecutive minutes whose changes add up to exactly k. The log holds up to 105 minutes. Which plan fits?
Choose one answer, then check.
Last, say a plan out loud for a problem you have not solved in this lesson.
A new problem: "Given meetings as [start, end] times, return the fewest rooms needed so that no two meetings in one room overlap. There are up to 104 meetings." Say your plan as you would in the round: the signals you read, the pattern and why it fits, the brute force you would name first, a clarifying question from the fine print, and the cost of each approach against the size limit.
Saved in this browser as you type.