Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Shortest Path proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Select a shortest-path method from edge costs and graph structure. Distances are discovered-path upper bounds; relaxation, finalization and negative-cycle handling depend on the selected method.
1 practice exercise1 interview problem
Recognize it when A question asks for minimum total cost or fewest moves between states.
Checking your account…
Shortest path is a family of problems. Use BFS for unit edges, Dijkstra for nonnegative weights, Bellman-Ford for possible negative weights, and DAG relaxation when a topological order exists.
A recorded distance is the cheapest path found so far, initially infinity except zero at the source. It becomes final only under the selected algorithm’s proof.
def relaxation_trace(node_count,edges,start):
distance=[None]*node_count;distance[start]=0;trace=[]
for source,target,weight in edges:
if distance[source] is not None:
candidate=distance[source]+weight
if distance[target] is None or candidate<distance[target]:distance[target]=candidate;trace.append(distance.copy())
return traceImplement relaxation_trace(node_count,edges,start). Process weighted directed edges once in order and return distances after every successful relaxation; unreachable is None. node_count is positive, start and all edge endpoints are valid vertex indices.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def relaxation_trace(node_count,edges,start):
distance=[None]*node_count;distance[start]=0;trace=[]
for source,target,weight in edges:
if distance[source] is not None:
candidate=distance[source]+weight
if distance[target] is None or candidate<distance[target]:distance[target]=candidate;trace.append(distance.copy())
return tracePredict the existing relaxation Lab in the deliberately unfavorable edge order shown. Its final snapshot is not the true shortest-path answer; it exposes why a general algorithm needs a processing or repetition proof.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Initialize | distance=[None]*node_count;distance[start]=0;trace=[] |
distance=[0, None, None] |
Only the source has a known path. |
| Skip first edge | if distance[source] is not None: |
edge 1->2 skipped |
Node 1 is not reachable in the current table yet. |
| Discover node 1 | candidate=distance[source]+weight;distance[target]=candidate;trace.append(distance.copy()) |
distance=[0, 3, None] |
The later 0->1 edge creates a usable prefix. |
| Direct node 2 path | candidate=distance[source]+weight;distance[target]=candidate;trace.append(distance.copy()) |
distance=[0, 3, 9] |
One pass does not revisit 1->2, so it misses the cheaper total 5. |
| Output | |
|---|---|
print(relaxation_trace(3, [[1, 2, 2], [0, 1, 3], [0, 2, 9]], 0)) |
[[0, 3, None], [0, 3, 9]] |
BFS’s layer order, Dijkstra’s nonnegative-cost order, DAG order and repeated Bellman-Ford passes are different ways to provide that missing guarantee. Name the guarantee instead of treating relaxation alone as an algorithm.
For edge u to v with weight w, propose distance[u] + w only when u is reachable. Replace distance[v] if the candidate is smaller and record predecessor when path reconstruction is required.
from collections import deque
def unweighted_distances(adjacency,start):
distance=[-1]*len(adjacency);distance[start]=0;queue=deque([start])
while queue:
node=queue.popleft()
for neighbor in adjacency[node]:
if distance[neighbor]==-1:distance[neighbor]=distance[node]+1;queue.append(neighbor)
return distanceImplement unweighted_distances(adjacency,start). Return shortest edge counts or -1 for unreachable nodes. adjacency is nonempty; start and every neighbor are valid vertex indices.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
from collections import deque
def unweighted_distances(adjacency,start):
distance=[-1]*len(adjacency);distance[start]=0;queue=deque([start])
while queue:
node=queue.popleft()
for neighbor in adjacency[node]:
if distance[neighbor]==-1:distance[neighbor]=distance[node]+1;queue.append(neighbor)
return distanceUse an explicit unreachable sentinel and never add weights to it. Negative edges invalidate Dijkstra’s finalization proof; reachable negative cycles mean no finite shortest distance for affected vertices.
Choose BFS instead of a weighted algorithm for unit edges. Choose Dijkstra for nonnegative weights, Bellman-Ford for possible negative weights, and topological relaxation for a weighted DAG.
Say: “These edge costs justify this algorithm. Distances are upper bounds, and relaxation improves one through a known reachable prefix.” State directedness, unreachable output, path reconstruction, and the precise complexity for the selected method.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Shortest Path proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Unweighted BFS | O(V + E) | O(V + E) | Unit-cost edges. |
| DAG relaxation | O(V + E) | O(V + E) | Includes obtaining a topological order. |
| Bellman-Ford | O(V + VE) | O(V + VE) | Includes initialization even with no edges; signed edges and reachable-cycle detection. |
O(V) distance/frontier state for BFS, plus the input graph; other methods have their own heap/matrix costs.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
None is not a numeric zero-cost path. Adding a weight to it raises TypeError.
Prevent it: Guard reachability before constructing a candidate.
candidate = distance[source] + weightcandidate = None if distance[source] is None else distance[source] + weightWhere you will hit this: Distance to the Nearest Source(opens in a new tab)
A discovered cost 4 should not be replaced by candidate 9. Relaxation minimizes rather than assigning every edge.
Prevent it: Update only if absent or strictly cheaper.
distance[target] = candidateif candidate < distance[target]: distance[target] = candidateWhere you will hit this: Distance to the Nearest Source(opens in a new tab)
A one-edge route can cost 8 while a two-edge route costs 3. Choosing fewer edges gives the wrong weighted answer.
Prevent it: Compare summed weights unless every edge has the same unit cost.
chosen = min(routes, key=lambda route: route[0])chosen = min(routes, key=lambda route: route[1])Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
python-docs · checked 2026-07-12
python-docs · checked 2026-07-27