Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Each bus route is a loop of stops. Find the fewest buses needed to travel from stop S to stop T (BFS over routes, not stops).

Problem: Each bus route is a loop of stops. Find the fewest buses needed to travel from stop S to stop T (BFS over routes, not stops).
from collections import deque, defaultdict
def buses(routes, S, T):
    if S == T: return 0
    at = defaultdict(list)
    for i, r in enumerate(routes):
        for s in r: at[s].append(i)
    q, seen_r, seen_s = deque([(S, 0)]), set(), {S}
    while q:
        s, d = q.popleft()
        for ri in at[s]:
            if ri in seen_r: continue
            seen_r.add(ri)
            for x in routes[ri]:
                if x == T: return d + 1
                if x not in seen_s: seen_s.add(x); q.append((x, d + 1))
    return -1
print(buses([[1, 5, 9], [3, 9, 12], [12, 15], [5, 15, 20]], 1, 20))
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: B. 2

From stop 1 the only route is [1, 5, 9]; at stop 5 you change to [5, 15, 20], which reaches 20: 2 buses. Counting stops (1 → 5 → 20) or going via 9 and 12 gives larger, wrong numbers; marking whole routes as used keeps BFS linear in the total route length.

More Coding Interview Problems questions

Exams that ask this topic