Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional

Problem: A tree has nodes 1–6 with weighted edges 1-2 (3), 1-3 (5), 2-4 (4), 2-5 (2), 3-6 (7). What is the weighted diameter (maximum over all pairs of the sum of edge weights on the path between them)?

  1. A. 12
  2. B. 19
  3. C. 4
  4. D. 21

Correct answer: B. 19

Two DFS passes (farthest node from any node, then farthest from that) give the path 4 → 2 → 1 → 3 → 6 = 4 + 3 + 5 + 7 = 19. The farthest distance from node 1 alone is 12, the unweighted diameter is 4 edges, and 21 sums every edge.

More Coding Interview Problems questions

Exams that ask this topic