Skip to the solution
HardDSA9 min read

How does the Bellman-Ford algorithm work?

844 views

The problem

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 parent V 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 so inf + (-5) stays inf, but still guard dist[u] != INF for 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.

  • graphs
  • shortest-path

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBellman-Ford round by round, worst and best edge order
PythonDetecting and printing a negative cycle

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 137 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How do you solve the trapping rain water problem?

Continue