Data Structures & AlgorithmsVery hardICPC regional · Product Company SDE

Problem: A tree has 7 nodes 1–7 with edges 1-2, 1-3, 2-4, 2-5, 3-6, 6-7. Each node is coloured red if its depth from node 1 is even and blue otherwise. How many pairs of nodes (unordered, distinct) have the same colour and are at distance exactly 2 in the tree?

  1. A. 9
  2. B. 6
  3. C. 12
  4. D. 21

Correct answer: B. 6

Nodes at distance 2 always have depths of the same parity, so the answer is just the number of distance-2 pairs: (1,4), (1,5), (1,6), (4,5), (2,3), (3,7) → 6. Counting all same-colour pairs gives 9, ordered pairs give 12, and 21 counts every pair.

More Coding Interview Problems questions

Exams that ask this topic