Skip to content
Preptima
mediumCodingConceptMidSeniorStaff

Find the cheapest route between two nodes in a weighted directed graph. Then tell me what breaks if one edge has a negative weight.

Dijkstra fails with negative edges because it finalises the current cheapest node under the assumption that no later edge can reduce it. Use Bellman-Ford when negative edges are possible, and reject graphs with negative cycles. It also connects shortest paths to the point an interviewer is testing.

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Dijkstra works only when edge weights are non-negative. A negative edge can make a node that was already settled become cheaper later, breaking the algorithm invariant. Use Bellman-Ford for negative edges, and report no finite shortest path if a reachable negative cycle exists.

Was this answer helpful?

Likely follow-ups

  • Every weight is 1. What is the right algorithm now, and why?
  • Weights are only ever 0 or 1. Can you beat the heap?
  • The graph contains a negative cycle. What should the function return, and how do you detect it?
  • You need cheapest routes between every pair of nodes, and some weights are negative. What do you run?

Related questions