Data Structures & AlgorithmsVery hardProduct company OA

How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices)

How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices)
from functools import lru_cache
n = 6
edges = [(0, 2), (1, 2), (2, 3), (1, 4), (4, 5)]
pre = [0] * n
for a, b in edges: pre[b] |= 1 << a
@lru_cache(None)
def ways(mask):
    if mask == (1 << n) - 1: return 1
    return sum(ways(mask | 1 << v) for v in range(n)
               if not mask >> v & 1 and pre[v] & mask == pre[v])
print(ways(0))
  1. A. 12
  2. B. 20
  3. C. 16
  4. D. 24

Correct answer: C. 16

ways(mask) = Σ ways(mask ∪ {v}) over vertices v not yet placed whose prerequisites are all in mask – 2⁶ states instead of 6! permutations. Constraints: 0 and 1 precede 2, 2 precedes 3, and 1 precedes 4 which precedes 5. Merging the chain 0/1 → 2 → 3 with the branch 4 → 5 (which only needs 1 first) gives 16 orders. Counting only orders of 0, 1, 2, 3 (ignoring 4 and 5) or multiplying independent chains naively gives the wrong options.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic