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?
  1. A. 7 7
  2. B. 5 5
  3. C. 7 5
  4. 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

Exams that ask this topic