Question presented to candidate: "How does the Bellman-Ford algorithm work? Implement it in Python for a directed graph given as an edge list that may contain negative weights, and tell me how you would detect a negative cycle."
What a strong answer should cover:
- Relax every edge V - 1 times; why V - 1 (a shortest simple path has at most V - 1 edges) and the round invariant.
- Negative-cycle detection with one extra round, and how to recover the cycle by walking
parentV times. - O(V ร E) time and O(V) extra space; early exit when a round changes nothing; comparison with Dijkstra.
- Only cycles reachable from the source are detected, and the virtual-source trick to find any cycle.
- Python specifics:
float("inf")absorbs additions soinf + (-5)staysinf, but still guarddist[u] != INFfor clarity; iterate a list of(u, v, w)tuples;any()for the detection pass.
Clarifying questions expected:
- "Can there be a negative cycle, and should I report it or print it?"
- "Is there a limit on the number of edges in a path?"
Code / implementation expected: Yes โ a Python bellman_ford(n, edges, source) returning distances and a negative-cycle flag, ideally with early exit.