Four interview problems that look like Dijkstra and change its cost rule. The move: name what a route costs, check that a step never lowers it, and add to the state whatever else the future needs.
You work on a social feed, a courier app and a flight planner. The four problems on this street all ask for the best route through a weighted graph. The Academy lesson solves the plain version, where a route costs the sum of its steps. Here the sum is replaced.
Read the table by its second and third columns. They are the only things that change from one problem to the next.
| Problem | A route costs | One more step gives | The search stops when |
|---|---|---|---|
| Network delay time | the sum of the minutes | cost + minutes | the quorum-th hub leaves the heap |
| Path with the minimum effort | its steepest step | max(cost, step) | the last block leaves the heap |
| Cheapest flights, one answer per leg count | the sum of the fares | cost + fare, from the last round | max_legs rounds are done |
| Swim in rising water | the minute it arrives | max(minute + 1, opening minute) | the last block leaves the heap |
The loop around the rule is the same each time: take the smallest entry, skip it if it is stale, and relax what leaves it. When you read a new problem, find the rule first.
Exercise · Predict the output: The steepest step. A ride costs its steepest road, and each road below shows that effort. This code is Dijkstra with the rule max(cost, step). What does it print?
import heapq
roads = [[(1, 4), (3, 5)], [(2, 4)], [(4, 4)], [(4, 5)], []]
best = [99] * 5
best[0] = 0
heap = [(0, 0)]
while heap:
cost, v = heapq.heappop(heap)
if v == 4:
print(cost)
break
if cost > best[v]:
continue
for w, step in roads[v]:
nxt = max(cost, step)
if nxt < best[w]:
best[w] = nxt
heapq.heappush(heap, (nxt, w))Before you code, answer three questions about the route.
First, what does a route cost, and what does one more step do to that cost? Write both as one line each. Second, can a step ever lower the cost? Third, is the cost all that the rest of the route needs to know?
| Problem | Cost of one more step | Never lowers it? | Is the cost enough? |
|---|---|---|---|
| Network delay time | cost + minutes | yes, minutes are at least 1 | yes |
| Path with the minimum effort | max(cost, step) | yes, a maximum never falls | yes |
| Swim in rising water | max(minute + 1, opening) | yes, it is at least minute + 1 | yes, waiting is inside the formula |
| Cheapest flights per leg count | cost + fare | yes, fares are at least 0 | no, the legs used also matter |
When a hub leaves the heap, its cost is final if no step can lower the cost of a route. Any other way to it passes through an entry still in the heap, which costs at least as much.
The first three rows pass all three questions, so the loop from the Academy lesson works with only the rule replaced. On the grid of heights [[5,6,9,1],[8,4,1,3],[2,6,8,4]], the rule max gives the right effort, 3.
The fourth row fails the third question. When the route may use at most k legs, a cost is not enough, and that is the subject of the next section.
A route costs its steepest step: the cost is the largest step so far, and it never falls as the ride goes on.
Exercise · Find the bug: The move takes a minute. A courier enters a hub no earlier than it opens, and each move takes one minute. Hubs 0 to n - 1, roads go both ways, and the courier starts at hub 0. Which line is wrong?
import heapq
def earliest_arrival(opens, roads):
n = len(opens)
near = [[] for _ in range(n)]
for a, b in roads:
near[a].append(b)
near[b].append(a)
best = [10**9] * n
best[0] = opens[0]
heap = [(opens[0], 0)]
while heap:
t, v = heapq.heappop(heap)
if t > best[v]:
continue
for w in near[v]:
arrive = max(t, opens[w])
if arrive < best[w]:
best[w] = arrive
heapq.heappush(heap, (arrive, w))
return best[n - 1]The Academy lesson Dijkstra's shortest paths builds the heap loop and proves why the smallest entry is final. BFS and DFS on a grid gives the grid walk. This street does not teach them again. It changes four things.
The rule is not a sum. On the heights above, adding the steps gives 9 for the best ride, and the steepest-step rule gives 3. Both are Dijkstra, with one line replaced.
Waiting is part of the cost. In the arrival example opens = [[1,9,3],[4,8,2],[6,7,5]], a courier who ignores the one minute per move reaches the goal at minute 7. The right answer is 8, because the formula must be max(minute + 1, opening).
The answer can be a position. In network delay time the answer is the minute of the quorum-th hub to leave the heap. Six users leave at minutes 0, 1, 3, 8, 9 and 10, and the quorum is 4. The answer is 8, and the search can stop there.
A limit adds to the state. Take roads 0-1 cost 1, 1-2 cost 1, 0-2 cost 5 and 2-3 cost 1, with at most 2 legs. The cheapest way to hub 2 costs 2 but uses both legs, so none is left for hub 3. The direct road costs 6 and fits.
With at most two legs, one cost per hub drops a dearer route that fits. Keep a cost for each leg count.
Exercise · Break it: One cost per hub with a leg limit. This runs Dijkstra with one cost per hub and skips any route that would need more than max_legs legs. Find an input where it returns the wrong answer.
import heapq
def cheapest_within(n, legs, source, target, max_legs):
near = [[] for _ in range(n)]
for a, b, fare in legs:
near[a].append((b, fare))
best = [10**9] * n
best[source] = 0
heap = [(0, 0, source)]
while heap:
cost, used, v = heapq.heappop(heap)
if cost > best[v]:
continue
if v == target:
return cost
for w, fare in near[v]:
if used + 1 <= max_legs and cost + fare < best[w]:
best[w] = cost + fare
heapq.heappush(heap, (cost + fare, used + 1, w))
return -1Solve them in this order. The first three change the rule or the stop, and the last one puts waiting into the cost.
Before you code each problem, write three lines: the cost of a route, the effect of one step, and what else the route needs. If the third is not empty, the state grows.
Give each problem about 25 minutes. Spend the first five on the three lines, and say them aloud as you would to an interviewer. Then name the stop.
Three edge cases return on every rung. A cost of zero is allowed in some rules, so the heap may hold ties. A target may be unreachable, and the answer is then a marker value. A hub can enter the heap many times, so keep the stale-entry check.
When a solution fails, check the three lines before the code. Most wrong answers on this street come from a rule that lets a step lower the cost, or from a state that leaves out something the route needs.
Checkpoint · Dijkstra patterns
Q1/5 A ride costs its steepest step. What does Dijkstra change for this rule?
Answer: B
Only the combining rule changes. The heap, the stale-entry check and the stop test stay as they were.
Q2/5 Which condition lets you trust the smallest heap entry as final?
Answer: B
Any other way to the vertex passes through an entry still in the heap, which costs at least as much. That argument needs only that a step cannot lower a cost.
Q3/5 A courier moves one minute per step and enters a hub no earlier than it opens. Which formula gives the arrival at the next hub?
Answer: C
The move takes a minute, and the hub may open later. The arrival is the later of the two.
Q4/5 Six users have seen a post at minutes 0, 1, 3, 8, 9 and 10, in that order. What is the minute when a quorum of 4 has seen it?
Answer: B
The users leave the heap in order of minute. The fourth one to leave has the answer, so the search can stop there.
Q5/5 A route may use at most 2 legs. Why can one cost per hub give a wrong answer?
Answer: C
The cost does not say how many legs are left. Keep the legs in the state, or run one round per leg.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.