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?- A. (3, 2)
- B. (3, 3)
- C. (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
- Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8…
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…
- Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get…
- Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1…
- Problem: Count connected components of an undirected graph given as an edge list on n nodes. cpp int find(vector<int>& p, int x) { return…
- Problem: Return the k-th largest value in a stream of scores using a min-heap of size k. python import heapq def kthlargest(a, k): h = []…