Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of semesters (Kahn's algorithm by layers).
Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of semesters (Kahn's algorithm by layers).
from collections import deque
def semesters(n, edges):
g = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges: g[u].append(v); indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0); sem = done = 0
while q:
sem += 1
for _ in range(len(q)):
u = q.popleft(); done += 1
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return sem if done == n else -1
print(semesters(7, [(0,2),(1,2),(2,3),(1,4),(4,5),(5,3),(3,6)]), semesters(3, [(0,1),(1,2),(2,0)]))What is printed?- A. 4 3
- B. 5 0
- C. 5 -1
- D. 6 -1
Correct answer: C. 5 -1
The longest chain is 1 → 4 → 5 → 3 → 6 (5 courses), so 5 semesters. In the second graph every course is on a cycle, nothing ever has in-degree 0, done < n, and the function returns −1.
More Coding Interview Problems questions
- Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor). python par = [-1, 0, 0, 1, 1, 2, 3, 3, 4…
- A COMPLETE binary tree has n nodes. Counting them by comparing the leftmost and rightmost depths at each node and recursing into only one…
- Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder. python def postfrompre(pre): i, out = 0…
- Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] −…
- Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a…
- Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]). python import heapq def…