Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths.

Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths.
from collections import deque
edges = [(0,1),(0,2),(1,3),(2,3),(3,4),(3,5),(4,5),(1,4)]
g = [[] for _ in range(6)]
for u, v in edges: g[u].append(v); g[v].append(u)
dist = [-1] * 6; ways = [0] * 6
dist[0], ways[0] = 0, 1
q = deque([0])
while q:
    u = q.popleft()
    for v in g[u]:
        if dist[v] == -1:
            dist[v] = dist[u] + 1; ways[v] = ways[u]; q.append(v)
        elif dist[v] == dist[u] + 1:
            ways[v] += ways[u]
print(dist[5], ways[5])
What is printed?
  1. A. 3 3
  2. B. 3 2
  3. C. 4 3
  4. D. 2 3

Correct answer: A. 3 3

Node 3 is at distance 2 with 2 ways (via 1 or 2); node 4 is also at distance 2 but only via 1 (1 way). Node 5 at distance 3 collects 2 ways from 3 plus 1 way from 4 = 3. The edge 4–5 counts because 4 is exactly one level before 5.

More Coding Interview Problems questions

Exams that ask this topic