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?
- A. Plain BFS is correct because all weights are 0 or 1, and it is the fastest option
- B. Only Floyd–Warshall is correct here, because 0-weight edges break Dijkstra
- C. Dijkstra fails with 0-weight edges, so Bellman–Ford's O(nm) ≈ 4·10¹⁰ is the only safe choice
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Which loop nests perform Θ(n log n) executions of work()? c / A / for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work(); / B / for…
- A full binary tree (every node has 0 or 2 children) has 10 internal nodes. How many leaves does it have?
- An undirected graph with V vertices and E edges is stored as adjacency lists. How many entries do all the lists hold in total?
- Which traversal should be used to free every node of a binary tree, so that no node is freed before its children?
- Keys 40, 20, 60, 10, 30, 50, 70, 25 are inserted into an empty BST. Then 20 is deleted (a node with two children is replaced by its…
- A 3-ary (ternary) heap is stored in a 0-indexed array where node i has children 3i + 1, 3i + 2 and 3i + 3. What is the index of the parent…