Data Structures & AlgorithmsVery hardCodeforces Div2 B · DP warm-up

Problem: Which statement correctly describes the diameter of a tree (the longest path between any two nodes) and how to compute it efficiently?

  1. A. It can only be computed with Floyd-Warshall, O(n^3)
  2. B. It equals the tree's height always
  3. C. Run BFS/DFS from any node to find the farthest node u, then run BFS/DFS again from u; the farthest node from u gives the diameter's endpoint -- O(n) total
  4. D. It requires trying all pairs of nodes, O(n^2)

Correct answer: C. Run BFS/DFS from any node to find the farthest node u, then run BFS/DFS again from u; the farthest node from u gives the diameter's endpoint -- O(n) total

This 'double-BFS/DFS' trick works because in a tree, the farthest node from an arbitrary start is always one endpoint of some longest path (diameter); two linear traversals suffice, giving O(n) total instead of checking all pairs.

More Coding Interview Problems questions

Exams that ask this topic