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?
- A. 1
- B. 2
- C. 3
- 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
- Problem: A row of 5 cells starts as [0, 0, 1, 0, 0]. Each step, every cell becomes the XOR of its two neighbours (cells outside the row…
- Problem: What is the exponent of the prime 3 in 100!? Use Legendre's formula, summing 100 // 3^k. Run the code. python print(sum(100 // 3…
- Problem: How many collinear triples of points does the 3 x 3 grid {0,1,2}^2 contain? Use the cross-product test below. python from…
- Problem: How many integers x in [1, 60] satisfy x ≡ 2 (mod 3) and x ≡ 3 (mod 4)? Run the code. python print(sum(1 for x in range(1, 61) if…
- Problem: How many unordered pairs from {1, 2, 3, 4, 5, 6} have XOR equal to 7? Run the code. python from itertools import combinations…
- Problem: How many palindromic substrings of length at least 1 does 'abcba' contain? Run the code. python s = 'abcba' print(sum(1 for i in…