Skip to content
mlmentorship

Finalize the cheapest pending path under nonnegative edge costs

Accept a node's first cheapest heap entry, skip later duplicates, then change sources or arrival queries.

Published · 15 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Finalize the cheapest pending path under nonnegative edge costs

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A positive node_count, a valid start node, and directed edges [source, target, cost] using IDs 1..node_count. Output. Return the latest earliest-arrival time among all nodes, or -1 if any node is unreachable from start. Rules. The signal starts at time zero. Edge costs are fixed and nonnegative; path cost is their sum. Edges are directed, so reverse travel is not implied. Preserve the edge list. This is shortest-path timing, not congestion-aware packet simulation. Example. Use edges [[1, 2, 1], [1, 3, 4], [2, 3, 2], [2, 4, 6], [3, 4, 1]]. Starting at node 1 with four nodes gives earliest arrivals [0, 1, 3, 4]; return 4.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Finalize shortest signal times by always popping the cheapest pending path.

Problem trace

A stale heap entry cannot improve an already finalized shorter distance

Input and goalFind when a signal from one node reaches every node in a weighted directed graph.
Initialize the source pathSeed only (0,1) in the heap. No node is finalized.
142611234
visitedfrontier(0,1)
inputn=4, start=1
visited
[]
edges
[1 -1-> 2, 1 -4-> 3, 2 -2-> 3, 2 -6-> 4, 3 -1-> 4]
edge label mode
weight

Recognize it
The input is a directed graph with nonnegative edge costs, and the task asks when a source reaches every node, so shortest paths from one source determine the answer.
Keep true
Whenever an unfinalized node is popped with the globally smallest pending cost, that cost is its shortest distance; duplicate heap entries for finalized nodes are safely ignored.
Reuse it
Reuse Dijkstra for nonnegative weighted routing: enqueue improved path candidates, trust only the first pop of each node, and derive the requested aggregate from finalized shortest distances.
Seed only (0,1) in the heap. No node is finalized. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does popping pending distance 4 for node 3 add no edges after distance 3 has been finalized?
Full interview answer 15 min read

Find when a signal can first reach every node in a directed network with fixed travel costs.

Problem

Input. A positive node_count, a valid start node, and directed edges [source, target, cost] using IDs 1..node_count.

Output. Return the latest earliest-arrival time among all nodes, or -1 if any node is unreachable from start.

Rules. The signal starts at time zero. Edge costs are fixed and nonnegative; path cost is their sum. Edges are directed, so reverse travel is not implied. Preserve the edge list. This is shortest-path timing, not congestion-aware packet simulation.

Example. Use edges [[1, 2, 1], [1, 3, 4], [2, 3, 2], [2, 4, 6], [3, 4, 1]]. Starting at node 1 with four nodes gives earliest arrivals [0, 1, 3, 4]; return 4.

Picture

The heap stores candidate routes; the finalized map stores accepted shortest distances. Several routes can name the same node.

Popped candidateAction
(0,1)Finalize 1; offer (1,2) and (4,3)
(1,2)Finalize 2; offer (3,3) and (7,4)
(3,3)Finalize 3; offer (4,4)
(4,3)Skip already finalized 3
(4,4)Finalize 4
(7,4)Skip already finalized 4

Problem trace

Separate queued estimates: stale entries do not replace the finalized minimum

Worked example: a queued estimate is stale when a shorter distance is already knownTwo entries can name the same node. With best distance 2, a later popped entry carrying distance 6 is stale and must not expand neighbors.Both queued estimates name one nodeand one best-distance recordQueued distances for the samenode26best distance2stale: skipEntry two may expand. Entry six mustnot expand or replace the knownshorter distance.
Read it this way: Two entries can name the same node. With best distance 2, a later popped entry carrying distance 6 is stale and must not expand neighbors. Does a later-popped six overwrite the already-known shorter distance two?
Reference drawing

Problem trace

A stale heap entry cannot improve an already finalized shorter distance

Worked example: a queued estimate is stale when a shorter distance is already knownTwo entries can name the same node. With best distance 2, a later popped entry carrying distance 6 is stale and must not expand neighbors.Both queued estimates name one nodeand one best-distance recordQueued distances for the samenode26best distance2stale: skipEntry two may expand. Entry six mustnot expand or replace the knownshorter distance.
Execution trace
Input and goalFind when a signal from one node reaches every node in a weighted directed graph.
Initialize the source pathSeed only (0,1) in the heap. No node is finalized.
142611234
visitedfrontier(0,1)
inputn=4, start=1
visited
[]
edges
[1 -1-> 2, 1 -4-> 3, 2 -2-> 3, 2 -6-> 4, 3 -1-> 4]
edge label mode
weight

Recognize it
The input is a directed graph with nonnegative edge costs, and the task asks when a source reaches every node, so shortest paths from one source determine the answer.
Keep true
Whenever an unfinalized node is popped with the globally smallest pending cost, that cost is its shortest distance; duplicate heap entries for finalized nodes are safely ignored.
Reuse it
Reuse Dijkstra for nonnegative weighted routing: enqueue improved path candidates, trust only the first pop of each node, and derive the requested aggregate from finalized shortest distances.
Seed only (0,1) in the heap. No node is finalized. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does popping pending distance 4 for node 3 add no edges after distance 3 has been finalized?
Read it this way: Two entries can name the same node. With best distance 2, a later popped entry carrying distance 6 is stale and must not expand neighbors. Does a later-popped six overwrite the already-known shorter distance two?

Why is the first pop final? Any supposedly cheaper route crosses from a finalized predecessor to a first unfinalized node. That predecessor already offered the corresponding prefix. Nonnegative remaining edges cannot make that prefix more expensive than the complete route. A cheaper complete route would therefore require a cheaper pending prefix, contradicting the minimum pop.

Code

This reference offers every outgoing candidate whose target is not finalized. It does not maintain a separate tentative-best table or perform decrease-key updates.

import heapq
from collections import defaultdict

def network_delay_time(times: list[list[int]], node_count: int, start: int) -> int:
   graph: dict[int, list[tuple[int, int]]] = defaultdict(list)
   for source, target, cost in times:
      graph[source].append((target, cost))

   distances: dict[int, int] = {}
   heap = [(0, start)]

   while heap:
      distance, node = heapq.heappop(heap)
      if node in distances:
         continue

      distances[node] = distance
      for neighbor, cost in graph[node]:
         if neighbor not in distances:
            heapq.heappush(heap, (distance + cost, neighbor))

   return max(distances.values()) if len(distances) == node_count else -1

Each node expands at most once, so each edge offers at most one candidate. The heap can hold entries, not just . For general multigraphs, bounds are time and space. For simple graphs, the usual bound follows.

Failure Check

Do not finalize at enqueue time or use FIFO order for unequal costs. Negative costs invalidate the proof. For [[1,2,1],[1,3,2],[3,2,-5],[2,4,2]], this method returns 3. The true maximum shortest arrival is 2; node 2 should arrive at -3.

Change the Sources

New task: Return each node’s nearest arrival from simultaneous zero-time sources.

Picture and change: Seed all sources before popping anything. Use the same valid node universe and nonnegative-cost contract. Unreached nodes return None, in node-ID order.

def arrival_times(times, node_count, starts):
   graph = {node: [] for node in range(1, node_count + 1)}
   for source, target, cost in times:
      graph[source].append((target, cost))
   heap = [(0, source) for source in set(starts)]
   heapq.heapify(heap)
   finalized = {}
   while heap:
      distance, node = heapq.heappop(heap)
      if node in finalized:
         continue
      finalized[node] = distance
      for neighbor, cost in graph[node]:
         if neighbor not in finalized:
            heapq.heappush(heap, (distance + cost, neighbor))
   return [finalized.get(node) for node in range(1, node_count + 1)]

Check: Edges [[1,2,3],[3,2,1]] with sources [1,3] return [0,1,0]. No sources returns all None; duplicate sources are coalesced. Keep the reference’s heapq import above. Reading a seed iterable also costs its length.

Use when: The nearest of several simultaneous sources matters.

Change the Query

New task: Return nodes reached by an inclusive deadline.

Picture and change: Compute arrivals first, then filter finite results.

def reached_by(times, node_count, starts, deadline):
   arrivals = arrival_times(times, node_count, starts)
   return [
      node for node, distance in enumerate(arrivals, 1)
      if distance is not None and distance <= deadline
   ]

Check: [[1,2,1],[2,3,2]], source [1], deadline 1 returns [1,2]. The boundary is inclusive; an unreachable node never passes. This wrapper does not stop the search early or change its shortest-path proof.

Use when: The arrival query changes, not the path costs.

Transfer Check

Why can two heap entries refer to the same node?

Answer

Different routes can be discovered before the cheapest one is popped. The finalized-node guard discards later duplicates safely under the nonnegative-cost contract. Compare equal-cost frontiers before replacing the heap with a queue.