Data Structures & AlgorithmsModerateProduct Company SDE · tree round

Problem: What is the time complexity of computing the diameter of a tree with n vertices by two breadth-first searches?

  1. A. O(n log n)
  2. B. O(n^2)
  3. C. O(n sqrt n)
  4. D. O(n)

Correct answer: D. O(n)

Each BFS visits every vertex and edge once, so two passes take linear time.

More Coding Interview Problems questions

Exams that ask this topic