FastPrepDiameter of an Acyclic Undirected Graph
Problems/Diameter of an Acyclic Undirected Graph

Diameter of an Acyclic Undirected Graph

Salesforce logoSalesforce● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source omits the callable interface and numeric bounds. The judged core task matches the visible source at about 95%.

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 vertices u and v.
  • A tree with one vertex has diameter 0.

Function

treeDiameter(n: int, edges: int[][]) → int

Examples

Example 1

n = 4edges = [[0,1],[1,2],[1,3]]return = 2

A longest path is 2 - 1 - 3, which contains two edges.

Example 2

n = 1edges = []return = 0

The single-vertex tree has no edges.

Constraints

  • 1 <= n <= 100000
  • edges.length = n - 1
  • 0 <= u, v < n
  • The input graph is connected and acyclic.

More Salesforce problems

  • Count Subarrays With Product Equal to KOA · Seen Nov 2026
  • Minimum No-Repeat Segments After One Character RemovalOA · Seen Nov 2026
  • Get Message StatusOA · Seen Nov 2026
All Salesforce interview questionsSee Salesforce hiring insights
Saved
class Solution {
    public int treeDiameter(int n, int[][] edges) {
      // Write your code here.
    }

}
Checking account…