Lesson 5 of 5
How hard problems are built
A hard problem is rarely a new idea. It is two patterns you already know working together, or one pattern with a promise that takes care to keep. Three moves find the parts, and this lesson uses them on two classic hards.
Open an unseen hard with three moves said out loud, from the brute force and its cost to the pattern that stops the repeated work
Solve trapping rain water with prefix maxima, then with two pointers in O(1) extra space
Use a list as its own hash map by giving every value from 1 to n a seat, as in first missing positive
Explain why a while loop inside a for loop can still cost O(n)
Take earlier hards apart into the patterns that build them
You open a problem marked Hard. A row of bars, rain, and one question: how much water stays? Nothing in the statement says hash map, window or heap. It is tempting to decide that hards need a trick you have never seen.
Most hards are built from parts you already own. They come in two shapes: two familiar patterns working together, or one familiar pattern with a sharp promise. This lesson builds two hards from those parts with the same four questions as always: the walk (the order you visit the data), the notebook (the few names you keep up to date), the promise (what stays true about the notebook after every step) and the cost (time and space). A sharp promise is one that takes real care to keep.
The first hard is built on the loop that keeps a running maximum, the one from module 1.
Three moves for an unseen hard
What do you do in the first minutes of a hard you have never seen? You need three moves, said out loud, in order, not a flash of insight. They spell out the plan the first lesson of this module gave for a problem that no signal fits (a signal is a phrase in the statement that points to a pattern).
- Say the brute force and its cost. The brute force is the slow, obvious answer that tries everything. It shows you understood the question and gives you something correct to improve.
- Find the work it repeats. Slow code usually computes the same thing again and again. Point at the line and say what it recomputes.
- Name the pattern that stops the repeat. Each kind of repeated work has a notebook that removes it, and you have met every one in the table below.
| The brute force keeps... | The notebook that stops it | Pattern |
|---|---|---|
| finding the sum or max of a prefix again | one running value, updated per item | the running maximum (module 1), prefix sums (module 3) |
| scanning the list to ask "is x here?" | a set or a dict | hash map (module 3) |
| rebuilding a window from scratch | add the item that enters, drop the one that leaves | sliding window (module 4) |
| searching every list's front for the smallest | a heap of the fronts | heap (module 9) |
The shape tells you where to spend your care. When two patterns work together, the hard part is making them fit. When one pattern is enough, the hard part is keeping its promise. The two hards below are one of each: rain water ends as two patterns working together, and first missing positive is one pattern with a sharp promise.
Rain water, version one: prefix maxima
Here is the first hard (LeetCode 42, Trapping Rain Water). Bars stand side by side with no gaps. Bar i is 1 unit wide and heights[i] units tall, a whole number from 0 up. Rain falls until no more can stay, and any water that reaches either end of the row runs off. How many units of water stay on the row? One unit fills a 1 by 1 square.
Here is heights = [3, 1, 2, 4, 0, 2] after the rain, drawn with # for bar and ~ for water, the bar positions underneath:
#
# ~ ~ #
# ~ # # ~ #
# # # # ~ #
0 1 2 3 4 5
Count the ~ marks: 5 units. Two stand over bar 1, one over bar 2, and two over bar 4.
The rule for one bar
Look at bar 1 alone. Water above it rises until it would spill over one side. The tallest bar on its left is bar 0, 3 tall. The tallest on its right is bar 3, 4 tall. Water spills over the lower of the two walls, so the level above bar 1 is 3. Bar 1 is 1 tall, so 3 - 1 = 2 units stand on it.
The same reasoning works for every bar. Let L be the height of the tallest bar at or left of bar i, and R the height of the tallest bar at or right of it. The water above bar i is min(L, R) - heights[i]. Counting bar i itself in both walls keeps that from going below 0: a bar taller than everything on one side is its own wall and holds nothing.
bar i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| height | 3 | 1 | 2 | 4 | 0 | 2 |
L, tallest at or left | 3 | 3 | 3 | 4 | 4 | 4 |
R, tallest at or right | 4 | 4 | 4 | 4 | 2 | 2 |
water, min(L, R) - height | 0 | 2 | 1 | 0 | 2 | 0 |
The water row adds up to 5, the same count as the picture. Try the rule on a new row.
A new row: heights = [2, 0, 4, 1, 3]. How many units of water stand above bar 3, the bar of height 1? Use the rule: the lower of the two walls, minus the bar's height. Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
From the brute force to prefix maxima
Move 1, the brute force: for each bar, scan everything to its left for L and everything to its right for R. In Python, max(heights[:i + 1]) is the tallest of bars 0 to i, and max(heights[i:]) the tallest from bar i to the end. Run it on our row.
It prints 5, the right answer. With n bars, each bar reads the whole row, so the n bars cost about n × n reads: O(n2) time.
Move 2, the repeated work: point at max(heights[:i + 1]). For bar 3 it reads bars 0 to 3. For bar 4 it reads bars 0 to 4 all over again, though only bar 4 is new. L at bar i is the larger of L at bar i - 1 and heights[i]. That is the running maximum from module 1, with one change: we write the running value down at every position.
Move 3, the pattern: a list whose position i holds the largest item from the start up to i is called prefix maxima. (A prefix is the part of a list from its start up to some position.) It is prefix sums from module 3, where position i holds the total of the items from 0 to i, with max in place of +. One walk from the left fills every L, the same walk from the right fills every R, and a third walk adds up the water.
The trace runs all three walks on our row, with left_wall holding every L and right_wall every R. Before you step through, cover the table above and guess both lists.
def trap_water(heights):n = len(heights)left_wall = [0] * nbest = 0for i in range(n):best = max(best, heights[i])left_wall[i] = bestright_wall = [0] * nbest = 0for i in range(n - 1, -1, -1):best = max(best, heights[i])right_wall[i] = bestwater = 0for i in range(n):water += min(left_wall[i], right_wall[i]) - heights[i]return water
(nothing printed yet)Why does best start at 0 here, when module 1 warned against it? A start value is safe only if it can never beat the real answer, and no bar is shorter than 0. For a list that may hold negative numbers, start at the first item instead.
The running maximum carries this whole hard. Write it as a function you can trust, on any list of integers.
Write prefix_max(nums), which returns a new list of the same length where position i holds the largest of nums[0] to nums[i]. For [3, 1, 2, 4, 0, 2] that is [3, 3, 3, 4, 4, 4]. The numbers can be negative, and the list can be empty. Use a loop, then press Watch it run to see the running maximum grow.
raise NotImplementedError, then press Run tests. Each check says what it expects.Rain water, version two: two pointers
The prefix version is correct and O(n). In the room, it is the version to write once you have named the brute force. Then expect the follow-up: can you do it in O(1) extra space? That means a fixed number of names however long the row, so no lists.
Each bar needs only its lower wall, not both. The second pattern comes in here: two pointers from module 4, two indexes that start at the two ends and step toward each other. Put left on the first bar and right on the last. Keep left_max, the height of the tallest bar left of left, and right_max, the height of the tallest bar right of right. Both start at 0, because no bar has been passed yet. A bar is settled once we know its lower wall exactly, so its water can be counted.
Here is one moment of the walk on some row: left_max is 2, right_max is 4, and bar left is 1 tall. Its left wall is max(2, 1), exactly 2. Its right wall is the tallest bar from left to the end, a stretch that includes every bar right of right, and one of those is 4 tall. So the right wall is at least 4, and the left wall, 2, is the lower one. The bar holds 2 - 1 = 1 unit. We never learned the exact right wall; we only needed to know it is not the lower one.
The same argument works whenever left_max <= right_max. The right wall of bar left covers bar left and every bar right of right, so it is at least max(heights[left], right_max). That is at least max(heights[left], left_max), the left wall. The left wall is the lower one, and we know it exactly, so bar left is settled: add its water and move left one step right. It is the fact behind container with most water in module 4: the shorter wall sets the level.
If instead left_max > right_max, the mirror argument settles bar right, which then moves one step left. Every step settles one bar, so the loop runs exactly n times.
Before you step through, predict the order in which the six bars are settled. One clue: after bar 0, left_max is 3 and right_max is still 0.
def trap_water(heights):left, right = 0, len(heights) - 1left_max, right_max = 0, 0water = 0while left <= right:if left_max <= right_max:left_max = max(left_max, heights[left])water += left_max - heights[left]left += 1else:right_max = max(right_max, heights[right])water += right_max - heights[right]right -= 1return water
(nothing printed yet)The whole argument rests on one comparison. Check that you can make it without the code.
Partway through the two-pointer walk on some row, left is 2, right is 6, left_max is 3 and right_max is 5. Bar 2 is 1 tall. What does the next step do?
Choose one answer, then check.
Then run the whole walk by hand on a new row, the way you would at a whiteboard with no run button.
Run the two-pointer walk by hand on heights = [1, 0, 3, 0, 2]. For each step, write left, right, left_max and right_max before the step, which bar is settled, and the water it adds. Reveal one step at a time and compare.
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.
Now write it from a blank editor. Start with the version you can write correctly; the speed test accepts both, because both are O(n).
Recap: two familiar patterns, working together. The brute force named the two walls: the water above a bar is min(L, R) minus its height. The repeated work in finding the walls pointed to the running maximum, kept as prefix maxima: O(n) time and O(n) space. Asking which wall each bar really needs brought in two pointers from both ends. The final version walks with two pointers and keeps a running maximum on each side, in O(n) time and O(1) space.
First missing positive: the list as its own hash map
The second hard (LeetCode 41, First Missing Positive) has the other shape: one pattern with a sharp promise. You get a list of integers in no particular order. Return the smallest positive integer (1, 2, 3, ...) that is not in it. [3, 1, 5, -2, 2, 1] holds 1, 2, 3 and 5, so the answer is 4. The limits are the hard part: O(n) time and O(1) extra space. You may rearrange the list.
Move 1, the brute force: try k = 1, 2, 3, ... and scan the list for each one.
def first_missing_slow(nums):
k = 1
while k in nums: # scans the list from the front
k += 1
return k
With n numbers there are up to n + 1 candidates, each a scan of up to n items: O(n2) time. Move 2: every k in nums rescans the same list. Move 3: a set answers "is k here?" in one step on average, so the time drops to O(n), but a set of n values costs O(n) space. Sorting first breaks the time limit instead: O(n log n). The hash map is the right pattern in the wrong place: the hard part is fitting it inside the list.
Bound the answer, then give every value a seat
n numbers hold at most n different values. If they hold every value from 1 to n, the answer is n + 1. If they miss one, the smallest value they miss is the answer, and it is one of 1 to n. So the answer is between 1 and n + 1, and any number below 1 or above n can be ignored. For [3, 1, 5, -2, 2, 1], n is 6, so the answer is between 1 and 7, and the -2 does not matter.
Only n values matter, and a list of length n has n positions. Give each value its own seat: seat v - 1 is for the value v. Seat 0 is for 1, seat 1 for 2, and so on. Then "is k present?" becomes "is seat k - 1 marked?": one look, like a dict lookup, except that the position comes straight from the value, with no hashing.
Write that first with a separate list of booleans. It costs O(n) space, but it is the exact notebook the final version hides inside nums.
Write first_missing(nums), which returns the smallest positive integer not in nums. Use a separate list present of n booleans, where n is the length of nums and present[v - 1] becomes True when the value v (from 1 to n) appears. Do not use a set or a dict: the point is the seats. This version uses O(n) extra space; the next part of the lesson removes it.
raise NotImplementedError, then press Run tests. Each check says what it expects.Seat each value in place
Now drop the separate list. Instead of marking seat v - 1, move the value v itself into seat v - 1. Walk the indexes left to right. At index i, if the value there is between 1 and n and its seat does not already hold it, swap it into its seat: the two items trade places. The value that comes back to index i may belong somewhere too, so stay at i and check again. Move on only when the value at i cannot move: it is out of range, or its seat already holds a copy.
In code the check is 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]. Python reads 1 <= x <= n as 1 <= x and x <= n. Both halves of the check are needed. The first keeps the seat real: for a 7 in a list of six numbers, nums[7 - 1] would raise an IndexError, and for a -2, nums[-3] would quietly read the third item from the end. and checks its left side first, so the second half runs only for a value that has a seat.
The swap line hides a second trap. Python's swap a, b = b, a works out the whole right side first, then assigns the targets from left to right. If the second target's index reads a value the first assignment changed, the second write lands in the wrong place. Predict this one carefully.
This is the tempting one-line swap, without a name for the seat. Type exactly what it prints. Python works out the whole right side first, then assigns the two targets from left to right, and it works out each target's index only when it reaches that target.
nums = [3, 1, 2]
i = 0
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
print(nums)
Save the seat in a name first, seat = nums[i] - 1, then swap nums[i] and nums[seat]. Here is the whole function on our list. Before you step through, guess how many swaps happen while i is still 0.
def first_missing_positive(nums):n = len(nums)for i in range(n):while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:seat = nums[i] - 1nums[i], nums[seat] = nums[seat], nums[i]for i in range(n):if nums[i] != i + 1:return i + 1return n + 1
(nothing printed yet)Why is a while loop inside a for loop still O(n)? Count swaps, not loop levels. Every swap puts one value into its own seat, and a value in its own seat never moves again, because the check skips a seat that already holds its value. n seats allow at most n swaps in the whole pass, plus one failed check per index. The trace made 3 swaps for 6 numbers.
This is the sharp promise: when the first loop ends, every value from 1 to n that appears anywhere in the list has a copy in its seat. Why does it hold? The while leaves index i only when its value is out of range or already has a copy in its seat, and a value in its own seat never moves. A later swap can change an earlier index only by seating a value there, and the value it pushes out lands at the current index, where the check looks at it. So no value from 1 to n is left stranded. The first seat that does not hold its own value names the answer, and if every seat is right, the answer is n + 1.
Put the whole function together. Two of the lines are the traps from this section.
Put the lines in order to build first_missing_positive(nums) with O(1) extra space: the first loop swaps every value from 1 to n into seat v - 1, and the second asks, for each k from 1 to n, whether seat k - 1 holds k. Indentation is part of each line. Two lines do not belong: they are the two traps from this section.
Add lines from the list below, in order.
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:for k in range(1, n + 1):return n + 1while 1 <= nums[i] <= n:if nums[k - 1] != k:nums[i], nums[seat] = nums[seat], nums[i]n = len(nums)seat = nums[i] - 1def first_missing_positive(nums):for i in range(n):return k
Now the full problem, from a blank editor.
No test here measures memory, so a set passes the tests, and so does sorting. Both miss the point of the problem, which is O(n) time with O(1) extra space.
Recap: one pattern, a sharp promise. The pattern is the hash map from module 3, kept inside the input. Bound the answer to 1 to n + 1, reserve seat v - 1 for the value v, swap values into their seats, and read the first wrong seat. The promise about seats is what makes the swaps correct.
Hards you have already met
What were the hards in earlier modules made of? Here are four, taken apart. A reminder of the parts: a sliding window is a run of neighbors whose two edges only move forward; a min-heap hands back its smallest item in O(log n) time, and a max-heap its largest; breadth-first search visits a graph ring by ring, nearest first.
| Hard | Its shape and parts | Where the difficulty sits |
|---|---|---|
| Minimum window substring (LeetCode 76, module 4) | Two patterns: a sliding window, and a dict of counts still needed | making them fit: one counter, missing, is 0 exactly when the window covers every needed letter |
| Merge k sorted lists (LeetCode 23, module 9) | Two patterns: merging by always taking the smallest front, and a min-heap of the k fronts | the heap holds exactly one front for each list that still has unmerged nodes |
| Word ladder (LeetCode 127, module 10) | Two patterns: breadth-first search, and a set of the words | the neighbors are not listed: you make each one-letter change and look it up in the set |
| Median of a stream (LeetCode 295, module 9) | One pattern, the heap, used twice: a max-heap for the smaller half, a min-heap for the larger half | the promise: every number in the low heap is at most every number in the high heap, and the low heap holds as many numbers as the high heap or one more |
Read the table as a recipe book. When a new problem arrives, ask which two of your patterns it needs, or which single pattern's promise it pushes hardest. Mediums are built the same way, and the next exercise uses one from module 3 to practice the moves.
This brute force counts the subarrays (runs of neighboring items) of nums that add up to k. The numbers can be negative.
def count_sum_k(nums, k):
count = 0
for start in range(len(nums)):
for end in range(start, len(nums)):
if sum(nums[start:end + 1]) == k:
count += 1
return count
It recomputes the sum of every run from scratch. Which notebook stops that repeat?
Choose one answer, then check.
Have the three moves ready as one sentence for when a hard question opens the round. The research digest's version, for the last two days before a loop, is: narrate, decompose, state the brute force, improve. Practice it on a hard from module 5, said as if you were seeing it for the first time.
An interviewer asks: "For a list nums and a size k, return the largest number in every window of k neighboring items, from left to right." Let n be the length of nums. Say your first three moves as you would in the room: the brute force and its cost, the work it repeats, and the pattern (or patterns) that stop the repeat. End with the cost of the faster version.
Saved in this browser as you type.
One more hard waits in this module's practice bank: Median of two sorted lists (LeetCode 4). Its parts are binary search from module 6, run over where to cut the shorter list, and the goal from the median of a stream: a split where every number on the left is at most every number on the right. Open it with the three moves before you read a hint.