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?
- A. Bellman-Ford, O(VE), because it handles any weights
- B. Dijkstra with a binary heap, O(E log V), because weights are non-negative
- C. Floyd-Warshall, O(V^3), for all pairs
- 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
- Problem: For the shortest subarray with sum at least S in an array of positive integers, a two-pointer sweep is used: extend the right…
- Problem: Weighted interval scheduling (each job has a start, finish and profit; choose a set of non-overlapping jobs to maximise profit)…
- Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from…
- Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS…
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 6 have gcd(a, b) = 1? python from math import gcd print(sum(1 for a in range(1…
- Problem: What does the following print? python print(sum(bin(i).count('1') for i in range(1, 16)))