Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many paths of length exactly 4 go from vertex 0 to vertex 0 in the complete graph K3? Run the code (walks allowed to repeat vertices).

Problem: How many paths of length exactly 4 go from vertex 0 to vertex 0 in the complete graph K3? Run the code (walks allowed to repeat vertices).
n = 3
adj = [[1 if i != j else 0 for j in range(n)] for i in range(n)]
P = [[int(i == j) for j in range(n)] for i in range(n)]
for _ in range(4):
    P = [[sum(P[i][k] * adj[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
print(P[0][0])
What is printed?
  1. A. 5
  2. B. 18
  3. C. 16
  4. D. 6

Correct answer: D. 6

(A⁴)[0][0] = (2⁴ + 2·(−1)⁴)/3 = 6 closed walks. Walks ending at a fixed other vertex number 5, the trace over all starts is 18, and 16 counts every walk from 0.

More Coding Interview Problems questions

Exams that ask this topic