Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which shortest-path algorithm is correct?

  1. A. Dijkstra with a binary heap – it handles negative edges
  2. B. Plain BFS – it ignores weights
  3. C. Prim's algorithm – it builds shortest paths
  4. D. Bellman–Ford (O(VE)) or SPFA – Dijkstra may finalise a node too early when an edge is negative

Correct answer: D. Bellman–Ford (O(VE)) or SPFA – Dijkstra may finalise a node too early when an edge is negative

Dijkstra assumes a popped distance can never improve, which a negative edge can break. Bellman–Ford relaxes all edges V − 1 times and is correct with negative edges (here O(VE) = 2 × 10¹⁰ is too slow, so in practice one uses SPFA or reweighting as in Johnson's algorithm, but Dijkstra alone is wrong). Prim builds a minimum spanning tree, not shortest paths.

More Coding Interview Problems questions

Exams that ask this topic