Data Structures & AlgorithmsVery hardProduct company OA
Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place any node whose prerequisites are all placed.
Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place any node whose prerequisites are all placed.
from functools import lru_cache
def count_orders(n, edges):
pre = [0] * n
for u, v in edges: pre[v] |= 1 << u
@lru_cache(None)
def f(mask):
if mask == (1 << n) - 1: return 1
return sum(f(mask | 1 << v) for v in range(n) if not mask >> v & 1 and pre[v] & mask == pre[v])
return f(0)
print(count_orders(4, [(0, 1), (0, 2), (1, 3), (2, 3)]), count_orders(5, [(0, 2), (1, 2), (2, 3)]), count_orders(3, []))What is printed?- A. 1 10 6
- B. 2 6 6
- C. 2 10 1
- D. 2 10 6
Correct answer: D. 2 10 6
pre[v] is the bitmask of v's prerequisites; v can be placed when pre[v] ⊆ mask. Diamond 0 → {1, 2} → 3: only 1 and 2 can swap → 2. Second DAG: 0 and 1 (in either order) before 2 before 3 gives 2 orders, and the free node 4 can go into any of 5 slots → 10. No edges → 3! = 6. Kahn's algorithm finds one order; counting needs this O(2ⁿ · n) DP (the problem is #P-hard in general).
More Coding Interview Problems questions
- Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM…
- Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start). python def…
- Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as…
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?
- Edge case: A helper collects items into a list using a default argument. python def collect(x, out=[]): out.append(x) return out a =…
- Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined…