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?
- A. It can only be computed with Floyd-Warshall, O(n^3)
- B. It equals the tree's height always
- 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
- 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
- Problem: A min-heap (binary heap) supports insert and extract-min in what time complexity, and what is the time to build a heap from n…
- Problem: To find the k largest elements among n numbers, which approach is asymptotically best when k is much smaller than n?
- Problem: An LRU (Least Recently Used) cache with O(1) get and put operations is classically implemented with which combination of data…
- Problem: Which statement about Kruskal's algorithm's overall time complexity is correct for a graph with V vertices and E edges?
- Problem: Topological sort is only defined for which kind of graph, and what happens if Kahn's algorithm is run on a graph that violates…
- Problem: Which best explains why merge sort is preferred over quicksort for sorting linked lists (as opposed to arrays)?