Problem set 4: graphs, heaps, greedy and DP
🌍 In real life. The last set mixes the biggest tools of the course: a crate of mangoes, a delivery app and a tea stall. Read each story for its clues before choosing.
The idea in one sentence: something that spreads one step at a time from several places at once is a BFS, "the k nearest/smallest" is a heap, and a series of choices calls for greedy only if you can show the local choice is always safe; otherwise use DP.
Its words:
- multi-source BFS: a BFS that starts from every source at once, so each ring is one more day
- heap: keeps the smallest item on top; a heap of size k keeps the k best seen so far
- safe greedy choice: a local choice you can prove never spoils the best answer
This set (Medium): graphs, heaps, greedy and DP
- Spoiling mangoes. In a crate laid out as a grid, a spoiled mango spoils its fresh neighbours (up, down, left, right) after one day. How many days until no fresh mango is left, or −1 if some can never spoil?
- The nearest riders. A delivery app knows where its riders are, as (x, y) points around the restaurant at (0, 0). Which k riders are nearest?
- Change at a tea stall. Tea costs 5 taka, the stall starts with no change, and customers pay with 5, 10 or 20 taka notes, one after another. Can every customer get the right change?
How to attack them, step by step:
- read the clues: "spreads each day", "the k nearest", "one choice after another"
- check the size: crates up to 100 × 100, up to 100,000 riders, up to 100,000 customers
- for a choice problem, look for a counterexample to the obvious greedy rule before trusting it (Lesson 56.1)
- code it and test the edge cases
The mangoes first. "Every step costs the same, and we want the fewest steps" is BFS's clue:
For the riders, the squared distances x² + y² of five riders at (3, 4), (3, 3), (3, 0), (1, 2) and (2, 3) are 25, 18, 9, 5 and 13. A min-heap hands back the smallest first, so two pops give the two nearest:
The nearest two are (1, 2) and (3, 0). Squared distances keep the order of real distances and avoid square roots.
Why these patterns fit. The mangoes spread in rings, day by day, from all spoiled mangoes at once: put every spoiled mango in the queue at day 0 (a multi-source BFS) and the day a mango is first reached is the day it spoils; any fresh mango never reached means −1. The riders need only the k smallest of many distances, which heapq.nsmallest keeps in a heap of size k. At the tea stall, a 20 needs 15 back: either 10 + 5 or 5 + 5 + 5. Spending the 10 first is always safe, because a 5 can pay any later change and a 10 can only help a later 20; so here greedy is right, and no DP is needed. (Lesson 56.1 showed coins where the greedy rule fails; there you would need DP.)
What it costs, by counting. A 100 × 100 crate has 10,000 cells; BFS visits each once and checks 4 neighbours: about 40,000 steps, O(rows × cols) time and memory. For 100,000 riders and k = 10, nsmallest does about 100,000 × log₂ 10, roughly 330,000 steps: O(n log k) time and O(k) memory, against O(n log n) for sorting everything. The tea stall is one pass: O(n) time, O(1) memory.
The three solutions together:
from collections import deque
def spoil_days(crate):
rows, cols = len(crate), len(crate[0]) if crate else 0
queue, fresh = deque(), 0
for r in range(rows):
for c in range(cols):
if crate[r][c] == "R":
queue.append((r, c, 0)) # every spoiled mango starts the BFS at day 0
elif crate[r][c] == "F":
fresh += 1
spoiled = set((r, c) for r, c, _ in queue)
days = 0
while queue:
r, c, d = queue.popleft()
days = max(days, d)
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and crate[nr][nc] == "F" and (nr, nc) not in spoiled:
spoiled.add((nr, nc))
fresh -= 1
queue.append((nr, nc, d + 1))
return days if fresh == 0 else -1 # some mango was never reached
import heapq
def k_closest(points, k):
# squared distance first, then the point itself, so ties have one fixed order
return heapq.nsmallest(k, points, key=lambda p: (p[0] * p[0] + p[1] * p[1], p))
def can_give_change(notes):
fives = tens = 0
for note in notes: # tea costs 5 taka
if note == 5:
fives += 1
elif note == 10:
if fives == 0:
return False
fives, tens = fives - 1, tens + 1
else: # a 20 needs 15 back
if tens and fives:
tens, fives = tens - 1, fives - 1 # spend the 10 first: 5s are more useful
elif fives >= 3:
fives -= 3
else:
return False
return True
print(spoil_days(["RFF", "FF.", ".FF"]), spoil_days(["RFF", ".FF", "F.F"]))
print(k_closest([(3, 4), (3, 3), (3, 0), (1, 2), (2, 3)], 2))
print(can_give_change([5, 5, 5, 10, 20]), can_give_change([5, 5, 10, 10, 20]))Mistakes and edge cases.
- one BFS per spoiled mango: running them one after another counts the days wrong; start them all together in one queue
- forgetting the unreachable fresh mango: count the fresh mangoes and check none is left, or the answer is wrong instead of −1
- a crate with no fresh mangoes: the answer is 0 days
- sorting all riders for k = 10: correct but O(n log n); a heap of size k does less work
- paying 5 + 5 + 5 before 10 + 5: uses up the 5s that later 10s need: [5, 5, 5, 5, 10, 20, 10] fails that way
Quiz
"Something spreads to its neighbours one step at a time from several places at once; how many steps until it is everywhere?" Which pattern?
- BFS with every starting place in the queue at step 0
- Dijkstra
- DFS from one place
What does this print?
from collections import deque def spoil_days(crate): rows, cols = len(crate), len(crate[0]) if crate else 0 queue, fresh = deque(), 0 for r in range(rows): for c in range(cols): if crate[r][c] == "R": queue.append((r, c, 0)) # every spoiled mango starts the BFS at day 0 elif crate[r][c] == "F": fresh += 1 spoiled = set((r, c) for r, c, _ in queue) days = 0 while queue: r, c, d = queue.popleft() days = max(days, d) for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)): if 0 <= nr < rows and 0 <= nc < cols and crate[nr][nc] == "F" and (nr, nc) not in spoiled: spoiled.add((nr, nc)) fresh -= 1 queue.append((nr, nc, d + 1)) return days if fresh == 0 else -1 # some mango was never reached print(spoil_days(["RFF", "FF.", ".FF"]), spoil_days(["R.F"]), spoil_days(["..R"]))What does heapq.nsmallest(k, points, ...) cost for n points?
- O(n log k) time, O(k) memory
- O(n²)
- O(k) time
A customer pays 20 taka and the stall has one 10 and three 5s. What should it give back?
- 10 + 5: keep the 5s, which can pay any later change
- 5 + 5 + 5
- Either: it never matters
can_give_change([5, 10, 20]) should be False (the 20 needs 15 back and only a 10 is left), but this answers True. Which line is wrong?
def can_give_change(notes): fives = tens = 0 for note in notes: if note == 5: fives += 1 elif note == 10: fives, tens = fives - 1, tens + 1 elif tens: tens -= 1 elif fives >= 3: fives -= 3 else: return False return True
Coding tasks
Spoiling mangoes. Write
spoil_days(crate):crateis a list of equal-length strings,"R"a spoiled mango,"F"a fresh one and"."an empty spot. Each day every spoiled mango spoils its fresh neighbours up, down, left and right. Return the number of days until no fresh mango is left, or-1if some fresh mango can never spoil.The nearest riders. Write
k_closest(points, k):pointsis a list of(x, y)tuples. Return thekpoints nearest to(0, 0)(by straight-line distance), nearest first; when two are equally near, the smaller point (as a tuple) comes first.Change at a tea stall. Write
can_give_change(notes): tea costs 5 taka, the stall starts with no money, andnoteslists what each customer pays, in order (5, 10 or 20). ReturnTrueif every customer can get the right change, elseFalse.