Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next.
Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next.
import heapq
def order(n, edges):
g = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges:
g[u].append(v); indeg[v] += 1
h = [i for i in range(n) if indeg[i] == 0]; heapq.heapify(h)
res = []
while h:
u = heapq.heappop(h); res.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0: heapq.heappush(h, v)
return res
print(*order(6, [(5,2),(5,0),(4,0),(4,1),(2,3),(3,1)]))What is printed?- A. 5 4 2 3 1 0
- B. 4 5 2 0 3 1
- C. 4 5 0 2 3 1
- D. 4 5 0 2 1 3
Correct answer: C. 4 5 0 2 3 1
Sources are 4 and 5; 4 runs first and frees nothing, then 5 frees 0 and 2. The heap picks 0 before 2, then 2 frees 3, and 3 frees 1, giving 4 5 0 2 3 1. '5 4 2 3 1 0' is a DFS-based topological order, valid but not the smallest-first one.
More Coding Interview Problems questions
- Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale…
- Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence…
- Problem: Return the length of the shortest string that contains both a and b as subsequences. python def scs(a, b): m, n = len(a), len(b)…
- Problem: The reflected binary Gray code of i is i ^ (i >> 1). At which position of the 3-bit Gray sequence does the code 6 (110) appear?…
- Problem: A permissions engine isolates bits of a mask. python x = 88 print(x & -x, x & (x - 1)) What is printed?
- Problem: Rearrange the digits of a version list into the next lexicographically greater permutation. python def nxt(a): i = len(a) - 2…