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?- A. 3 3
- B. 3 2
- C. 4 3
- 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
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…
- Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight. python edges =…
- Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots…
- Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than…
- Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order. python def ways(coins, amt): dp…
- Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome. python…