Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time v is discovered. Compare it with Dijkstra.
Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time v is discovered. Compare it with Dijkstra.
import heapq
from collections import deque
def bfs_edges(n, edges, s, t):
adj = [[] for _ in range(n)]
for u, v, w in edges: adj[u].append((v, w)); adj[v].append((u, w))
dist = {s: 0}; q = deque([s])
while q:
u = q.popleft()
for v, w in adj[u]:
if v not in dist: dist[v] = dist[u] + w; q.append(v)
return dist[t]
def dijkstra(n, edges, s, t):
adj = [[] for _ in range(n)]
for u, v, w in edges: adj[u].append((v, w)); adj[v].append((u, w))
d = [float("inf")] * n; d[s] = 0; h = [(0, s)]
while h:
du, u = heapq.heappop(h)
if du > d[u]: continue
for v, w in adj[u]:
if du + w < d[v]: d[v] = du + w; heapq.heappush(h, (d[v], v))
return d[t]
E = [(0, 1, 5), (0, 2, 1), (2, 3, 1), (3, 1, 1), (1, 4, 2)]
print(bfs_edges(5, E, 0, 4), dijkstra(5, E, 0, 4))What is printed?- A. 7 7
- B. 5 5
- C. 7 5
- D. 4 5
Correct answer: C. 7 5
BFS minimises the number of edges, not total weight: it fixes node 1 at 5 through the direct heavy edge, giving 5 + 2 = 7. Dijkstra finds 0 → 2 → 3 → 1 → 4 = 1 + 1 + 1 + 2 = 5. With small integer weights, Dijkstra (O((n + m) log n)) or a bucket queue / splitting edges into unit edges both pass; BFS is only valid when all weights are equal (or 0/1 with a deque).
More Coding Interview Problems questions
- Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a…
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…