Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph.

Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph.
from collections import deque
def count_sp(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges: adj[u].append(v); adj[v].append(u)
    dist = [-1] * n; ways = [0] * n
    dist[0], ways[0] = 0, 1; q = deque([0])
    while q:
        u = q.popleft()
        for v in adj[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]
    return dist[n - 1], ways[n - 1]
print(count_sp(6, [(0, 1), (0, 2), (1, 3), (2, 3), (1, 4), (3, 5), (4, 5), (2, 4)]))
What is printed?
  1. A. (3, 2)
  2. B. (3, 3)
  3. C. (4, 4)
  4. D. (3, 4)

Correct answer: D. (3, 4)

BFS layers: 0 | 1, 2 | 3, 4 (each reachable from both 1 and 2, so 2 ways each) | 5 (from 3 and 4: 2 + 2 = 4 ways). A node's count adds the counts of all neighbours exactly one layer earlier. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic