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?- A. 3
- B. 2
- C. 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
- Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by…
- Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity. python def single(a): lo, hi = 0…
- Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final…
- Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max…
- Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index. python def…
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…