Data Structures & AlgorithmsModerateCodeforces Div2 C · shortest paths

Problem: A road graph has V = 10^5 vertices and E = 3 * 10^5 edges, all weights non-negative, and you need shortest paths from one source. Which approach is the right one, and why?

  1. A. Bellman-Ford, O(VE), because it handles any weights
  2. B. Dijkstra with a binary heap, O(E log V), because weights are non-negative
  3. C. Floyd-Warshall, O(V^3), for all pairs
  4. D. BFS in O(V + E), because the graph is unweighted

Correct answer: B. Dijkstra with a binary heap, O(E log V), because weights are non-negative

Bellman-Ford would need about 3 * 10^10 relaxations, which is too slow. Non-negative weights let Dijkstra finalise vertices in order, so the heap version runs in O(E log V) time.

More Coding Interview Problems questions

Exams that ask this topic