Data Structures & AlgorithmsVery hardProduct company OA

A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of tolled roads from junction 1 to every junction, time limit 1 s. Which statement is correct?

  1. A. Plain BFS is correct because all weights are 0 or 1, and it is the fastest option
  2. B. Only Floyd–Warshall is correct here, because 0-weight edges break Dijkstra
  3. C. Dijkstra fails with 0-weight edges, so Bellman–Ford's O(nm) ≈ 4·10¹⁰ is the only safe choice
  4. D. A 0-1 BFS with a deque runs in O(n + m) and is correct; plain BFS by edge count is wrong, and Bellman–Ford is too slow

Correct answer: D. A 0-1 BFS with a deque runs in O(n + m) and is correct; plain BFS by edge count is wrong, and Bellman–Ford is too slow

Plain BFS minimises the number of roads, not the number of tolls – a long free detour beats one toll. Dijkstra is perfectly correct with zero weights (only negative weights break it), at O((n + m) log n); 0-1 BFS is the same idea with a deque: push to the front for weight 0 and the back for weight 1, so each vertex is finalised in order – O(n + m). Bellman–Ford at ~4·10¹⁰ and Floyd–Warshall at n³ ≈ 8·10¹⁵ are hopeless.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic