Problem · Graph
Diameter of an Acyclic Undirected Graph
Learn this problemProblem statement
You are given a connected, undirected, acyclic graph, so the graph is a tree. The tree has n vertices labeled from 0 to n - 1 and n - 1 edges.
The diameter of the tree is the maximum number of edges on any simple path between two vertices.
Implement treeDiameter(n, edges) and return the tree's diameter.
edges[i] = [u, v]denotes an undirected edge between verticesuandv.- A tree with one vertex has diameter
0.
Function
treeDiameter(n: int, edges: int[][]) → intExamples
Example 1
n = 4edges = [[0,1],[1,2],[1,3]]return = 2A longest path is 2 - 1 - 3, which contains two edges.
Example 2
n = 1edges = []return = 0The single-vertex tree has no edges.
Constraints
1 <= n <= 100000edges.length = n - 10 <= u, v < n- The input graph is connected and acyclic.
More Salesforce problems
- Optimal Account BalancingPHONE SCREEN · Seen Jul 2026
- Longest Increasing SubsequencePHONE SCREEN · Seen Jul 2026
- Maximal SquarePHONE SCREEN · Seen Jul 2026
- Maximum Barbell WeightOA · Seen Jul 2026
- Minimum No-Repeat Segments After One Character RemovalOA · Seen Jul 2026
- Minimum Operations to ZeroOA · Seen Jul 2026
- Minimize Total Input Cost (for LTMS)OA · Seen Jun 2026
- Count Prime StringsONSITE INTERVIEW · Seen Jun 2026