Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many paths of length 3 exist in a complete graph K4 that start and end at different vertices? Run the code (count ordered walks v0, v1, v2, v3 with v0 != v3 and consecutive vertices distinct).

Problem: How many paths of length 3 exist in a complete graph K4 that start and end at different vertices? Run the code (count ordered walks v0, v1, v2, v3 with v0 != v3 and consecutive vertices distinct).
n = 4
print(sum(1 for a in range(n) for b in range(n) for c in range(n) for d in range(n) if a != b and b != c and c != d and a != d))
What is printed?
  1. A. 108
  2. B. 24
  3. C. 84
  4. D. 256

Correct answer: C. 84

Walks with distinct neighbours: 4 · 3 · 3 · 3 = 108, minus the 24 closed walks with v₀ = v₃, gives 84. 108 forgets the end condition, 24 counts paths with all vertices distinct, and 4⁴ = 256 ignores every constraint.

More Coding Interview Problems questions

Exams that ask this topic