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?
  1. A. 1 10 6
  2. B. 2 6 6
  3. C. 2 10 1
  4. 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

Exams that ask this topic