Data Structures & AlgorithmsHardICPC regional · Product Company SDE

Problem: On a tree with 9 nodes labelled 1–9, edges 1-2, 1-3, 2-4, 2-5, 3-6, 6-7, 6-8, 8-9, count the unordered pairs of nodes whose path has exactly 3 edges.

  1. A. 9
  2. B. 14
  3. C. 7
  4. D. 24

Correct answer: C. 7

BFS from every node (or depth bookkeeping) finds 7 pairs at distance exactly 3, e.g. (4, 3), (1, 7), (2, 6), (1, 8), (3, 9). Counting distance 2 instead gives 9, counting ordered pairs gives 14, and counting all pairs within distance 3 gives 24.

More Coding Interview Problems questions

Exams that ask this topic