Data Structures & AlgorithmsModerateTCS NQT · graph counting

Problem: How many topological orders does the DAG with edges 0->2, 1->2, 2->3 on vertices 0..3 have? Run the brute-force code.

Problem: How many topological orders does the DAG with edges 0->2, 1->2, 2->3 on vertices 0..3 have? Run the brute-force code.
from itertools import permutations
edges = [(0, 2), (1, 2), (2, 3)]
print(sum(1 for p in permutations(range(4)) if all(p.index(u) < p.index(v) for u, v in edges)))
What is printed?
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: B. 2

Vertices 0 and 1 must both precede 2, which precedes 3, and 0 and 1 can be swapped, giving 2 orders. Counting all permutations (24) ignores the edges.

More Coding Interview Problems questions

Exams that ask this topic