Diameter of an Unweighted Tree

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given n vertices labeled 0 through n - 1 joined by n - 1 bidirectional unweighted links edges that form a single tree, compute the diameter of the tree.

In an unweighted tree, every pair of vertices is connected by a unique simple path (a walk with no repeated vertices or links). The tree's diameter equals the largest link count across all simple paths in the tree. When the tree has only a single vertex (n = 1 and edges = []), no links can be traversed, so the diameter is 0.

Implement:

def tree_diameter(n: int, edges: list[list[int]]) -> int:
    ...

Each entry [u, v] in edges connects vertex u and vertex v in both directions. Return the maximum link count along any simple path.

Examples

Example 1

n = 7
edges = [[0, 2], [2, 1], [2, 3], [3, 4], [4, 5], [3, 6]]

Output:

4

Walk-through: Vertex 2 connects leaves 0 and 1 on one side to vertex 3 on the other, while vertex 3 branches to leaf 6 and the two-edge arm 3 - 4 - 5. The longest simple paths are 0 - 2 - 3 - 4 - 5 and 1 - 2 - 3 - 4 - 5, each spanning 4 edges.

Example 2

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

Output:

2

Walk-through: Vertex 4 acts as a central hub directly connected to leaves 0, 1, 2, and 3. Every path between two distinct leaves crosses 2 edges through vertex 4 (such as 0 - 4 - 2).

Constraints

  • 1 <= n <= 100_000
  • len(edges) == n - 1
  • Every edge [u, v] satisfies 0 <= u, v < n and u != v
  • edges forms a single connected, cycle-free undirected graph

Step-by-step walkthrough

  1. Understand the goal and what "diameter" means

    We are given n nodes labeled 0 through n - 1 connected by n - 1 undirected edges [u, v] with no cycles — an undirected tree. Because a tree has no loops, every pair of nodes is connected by one unique simple path (a walk that never repeats a node or edge).

    A tree's diameter measures the largest edge count across all simple paths in the tree:

    • A single node (n = 1, edges = []) has 0 edges -> diameter 0.
    • Two connected nodes (n = 2, edges = [[0, 1]]) have 1 edge -> diameter 1.

    Watch out for a classic beginner trap: the longest path in the tree does not have to start at node 0, or even pass through node 0! Look at this 8-node tree where node 0 sits on a short side twig:

        4 - 3 - 2 - 1 - 5 - 6 - 7    <-- longest path (4 to 7) has 6 edges!
                    |
                    0                <-- farthest distance from node 0 is only 4!
    

    Here, measuring distances only from node 0 gives 4 (from 0 to 4 or 7), missing the true diameter of 6 (from 4 to 7). And because n can be as large as 100,000, our solution must run in O(n) linear time without hitting Python's recursion limit on a 100,000-node chain.

  2. Why the brute-force approach is too slow

    How do we measure distances from a single starting node in an unweighted graph? We run breadth-first search (BFS), which explores nodes layer by layer (distance 0, then 1, then 2, and so on) in O(n) time.

    A straightforward brute-force solution runs BFS starting from every node 0, 1, ..., n - 1 and keeps the largest distance seen anywhere. That is guaranteed to find the diameter, and we can use it to test small random trees, but n runs of O(n) BFS take O(n^2) time — roughly 10^10 operations when n = 100,000, which will time out.

    Notice why O(n^2) is wasteful: if someone simply whispered one endpoint (say node 4 above) of a longest path to us, a single BFS starting at 4 would walk all the way to 7 and hand us the diameter in O(n) time! So the whole problem boils down to: how can we find one true endpoint of a longest path fast?

  3. Key insight: any farthest node is already a diameter endpoint

    Imagine the tree is built out of string and wooden beads lying on a table:

    1. Pass 1: Pinch any bead (say bead 0) and lift the tree up so gravity pulls every branch downward. Whichever bead hangs the lowest (end_a) must be one tip of a longest path in the entire tree!
    2. Pass 2: Now grab the tree by end_a and lift it up again. The entire longest path now hangs straight down from end_a to the new lowest bead end_b, and its length is the exact diameter!

    Why is end_a guaranteed to be an endpoint of a longest path, even when node 0 is on a side twig? Picture any true longest path u --- v in the tree. Because a tree has only one route between paths, the walk starting at 0 joins u --- v at some junction node x (which could be on u --- v itself):

                    0  (start of Pass 1)
                    |
            u ----- x --------- v     (suppose u---v is a longest path)
                     \
                      \-------- end_a (farthest node from 0)
    

    Think about the journey from 0: to reach u or v, we first walk 0 -> x and then finish along x -> u or x -> v. Since end_a is at least as far from 0 as v is, the branch after x toward end_a must be at least as long as x -> v (and even if end_a branched off earlier above x, its detour is even longer!). That means swapping the x -> v half for the route to end_a gives a path u -> x -> ... -> end_a that is at least as long as u --- v — proving end_a is itself an endpoint of a longest path!

  4. Build the adjacency list and iterative BFS helper

    To walk from any node to its neighbors in O(1) per edge, we first convert edges into an adjacency list adj, where adj[u] holds every neighbor connected to u. Because edges have no direction, [u, v] adds v to adj[u] and u to adj[v].

    Inside bfs_farthest(adj, start_node), we pay attention to three practical details: 1. Distance + visited in one list: Initialize dist = [-1] * len(adj) and dist[start_node] = 0. A value of -1 means "not visited yet," preventing the search from bouncing back and forth across the same undirected edge. 2. Use collections.deque, not list.pop(0): A deque (double-ended queue) pops from the front in O(1) constant time, whereas list.pop(0) shifts every remaining element in O(n) time. 3. Iterative loop, not recursion: A 100,000-node straight line has depth 99,999, which would crash a recursive DFS with RecursionError (Python's default stack limit is 1,000). A while queue: loop uses heap memory safely at any depth.

    from collections import deque
    
    
    def build_adjacency(n: int, edges: list[list[int]]) -> list[list[int]]:
        """Build undirected adjacency lists for nodes 0 .. n - 1."""
        # adj[u]: list of neighbor node IDs directly connected to node u.
        adj: list[list[int]] = [[] for _ in range(n)]
        for u, v in edges:
            # Add both directions because edges can be traversed either way.
            adj[u].append(v)
            adj[v].append(u)
        return adj
    
    
    def bfs_farthest(adj: list[list[int]], start_node: int) -> tuple[int, int]:
        """Return (farthest_node, max_edge_distance) starting from start_node."""
        # dist[v]: edge count from start_node to v, or -1 if v has not been visited yet.
        dist = [-1] * len(adj)
        dist[start_node] = 0
    
        # queue: FIFO deque of visited nodes whose neighbors still need to be explored.
        # Iterative BFS with deque avoids Python's 1000-call recursion limit on long chains.
        queue = deque([start_node])
        farthest_node = start_node
    
        while queue:
            curr = queue.popleft()
            if dist[curr] > dist[farthest_node]:
                farthest_node = curr
    
            for neighbor in adj[curr]:
                # Checking dist[neighbor] == -1 prevents walking backward to our parent.
                if dist[neighbor] == -1:
                    dist[neighbor] = dist[curr] + 1
                    queue.append(neighbor)
    
        return farthest_node, dist[farthest_node]
    
  5. Combine the two BFS passes

    With build_adjacency and bfs_farthest ready, tree_diameter is just three steps: handle the 0-edge base case n <= 1, run Pass 1 from node 0 to locate endpoint end_a, and run Pass 2 from end_a to measure the diameter.

    def tree_diameter(n: int, edges: list[list[int]]) -> int:
        # A tree with 0 or 1 node has no edges, so its longest path has 0 edges.
        if n <= 1:
            return 0
    
        adj = build_adjacency(n, edges)
    
        # Pass 1: Any farthest node from node 0 is guaranteed to be one endpoint
        # of a longest path in the tree.
        end_a, _ = bfs_farthest(adj, 0)
    
        # Pass 2: Measuring the farthest distance from end_a sweeps across the
        # entire longest path to its opposite endpoint.
        _, diameter = bfs_farthest(adj, end_a)
        return diameter
    
  6. Trace Example 1 step by step

    Let's trace n = 7, edges = [[0, 2], [2, 1], [2, 3], [3, 4], [4, 5], [3, 6]]:

    Tree shape:
        1 --- 2 --- 3 --- 4 --- 5
              |     |
              0     6
    
    Pass 1 (start_node = 0):
      Layer 0: visit 0               -> dist[0] = 0, farthest = 0
      Layer 1: visit 2 (from 0)      -> dist[2] = 1, farthest = 2
      Layer 2: visit 1, 3 (from 2)   -> dist[1] = 2, dist[3] = 2, farthest = 1
      Layer 3: visit 4, 6 (from 3)   -> dist[4] = 3, dist[6] = 3, farthest = 4
      Layer 4: visit 5 (from 4)      -> dist[5] = 4, farthest = 5
      Result of Pass 1: end_a = 5
    
    Pass 2 (start_node = 5):
      Layer 0: visit 5               -> dist[5] = 0
      Layer 1: visit 4               -> dist[4] = 1
      Layer 2: visit 3               -> dist[3] = 2
      Layer 3: visit 2, 6            -> dist[2] = 3, dist[6] = 3
      Layer 4: visit 0, 1            -> dist[0] = 4, dist[1] = 4
      Result of Pass 2: diameter = 4 (path 5 - 4 - 3 - 2 - 0 or 5 - 4 - 3 - 2 - 1)
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def build_adjacency(n: int, edges: list[list[int]]) -> list[list[int]]:
        """Build undirected adjacency lists for nodes 0 .. n - 1."""
        # adj[u]: list of neighbor node IDs directly connected to node u.
        adj: list[list[int]] = [[] for _ in range(n)]
        for u, v in edges:
            # Add both directions because edges can be traversed either way.
            adj[u].append(v)
            adj[v].append(u)
        return adj
    
    
    def bfs_farthest(adj: list[list[int]], start_node: int) -> tuple[int, int]:
        """Return (farthest_node, max_edge_distance) starting from start_node."""
        # dist[v]: edge count from start_node to v, or -1 if v has not been visited yet.
        dist = [-1] * len(adj)
        dist[start_node] = 0
    
        # queue: FIFO deque of visited nodes whose neighbors still need to be explored.
        # Iterative BFS with deque avoids Python's 1000-call recursion limit on long chains.
        queue = deque([start_node])
        farthest_node = start_node
    
        while queue:
            curr = queue.popleft()
            if dist[curr] > dist[farthest_node]:
                farthest_node = curr
    
            for neighbor in adj[curr]:
                # Checking dist[neighbor] == -1 prevents walking backward to our parent.
                if dist[neighbor] == -1:
                    dist[neighbor] = dist[curr] + 1
                    queue.append(neighbor)
    
        return farthest_node, dist[farthest_node]
    
    
    def tree_diameter(n: int, edges: list[list[int]]) -> int:
        # A tree with 0 or 1 node has no edges, so its longest path has 0 edges.
        if n <= 1:
            return 0
    
        adj = build_adjacency(n, edges)
    
        # Pass 1: Any farthest node from node 0 is guaranteed to be one endpoint
        # of a longest path in the tree.
        end_a, _ = bfs_farthest(adj, 0)
    
        # Pass 2: Measuring the farthest distance from end_a sweeps across the
        # entire longest path to its opposite endpoint.
        _, diameter = bfs_farthest(adj, end_a)
        return diameter
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture an undirected tree (a connected network of n nodes and n - 1 two-way links with no loops) as a floppy cluster of beads tied together with pieces of string. If you pinch any random bead — say bead 0 — and hold it up in the air, gravity pulls the strings downward, and whichever bead dangles the lowest (end_a) is guaranteed to be one tip of the longest string in the whole cluster. If you then pinch end_a and lift the cluster a second time, that entire longest path stretches straight down from end_a to the opposite tip, giving us the diameter (the maximum number of edges along any simple path, meaning a walk that never repeats a node).

The naive approach runs a breadth-first search (BFS) — a traversal that visits nodes in expanding rings of distance 0, 1, 2, ... — starting separately from every node 0 .. n - 1. That checks all pairs accurately, but n searches of O(n) work cost O(n^2) time, which means roughly 10^10 steps when n = 100,000. Equally tempting is running just one BFS from node 0, which fails whenever node 0 sits near the middle of the tree (a 3-node chain 1 - 0 - 2 has distance 1 from 0, even though 1 to 2 is 2 edges!). Doing two BFS passes gets the exact diameter in O(n) linear time.

Let's trace Example 2, a 5-node star centered at node 4: edges = [[4, 0], [4, 1], [4, 2], [4, 3]]. 1. Pass 1 from node 0: Distance is 0 at node 0, 1 at the hub 4, and 2 at leaves 1, 2, and 3. A farthest node found is end_a = 1 (at distance 2). 2. Pass 2 from node 1: Distance is 0 at 1, 1 at 4, and 2 at 0, 2, and 3. The maximum distance reached in Pass 2 is 2, which is the diameter (1 - 4 - 2).

Complexity

  • Time — O(n): Building the adjacency list (an array where adj[u] lists all neighbors directly attached to u) loops once over n - 1 edges. Each of the two BFS passes enqueues and pops each of the n nodes once and inspects each undirected edge twice (once from each end, 2 * (n - 1) neighbor checks per pass), so every step is directly proportional to n.
  • Space — O(n): The adjacency list stores 2 * (n - 1) integers across n lists, dist holds n integers, and the deque (a double-ended queue supporting O(1) appends at the back and O(1) pops from the front) holds at most n node IDs at once.

Edge cases

  • Single node (n = 1, edges = []): There are zero edges, so the longest path has 0 edges (not 1 — we count edges, not nodes!).
  • Single edge (n = 2, edges = [[1, 0]]): Pass 1 goes 0 -> 1 and Pass 2 goes 1 -> 0, returning 1.
  • Star graph (all nodes attached to one hub): As soon as n >= 3, every longest path goes leaf -> hub -> another leaf, returning 2 regardless of whether n is 3 or 100,000 and regardless of which node ID is the hub.
  • Node 0 on a short side branch: Pass 1 still climbs out of the side branch onto one true endpoint of the main trunk, and Pass 2 measures the full trunk length.
  • Long 100,000-node chain: Diameter is 99,999. Because bfs_farthest uses an iterative while queue: loop instead of recursion, it never triggers Python's RecursionError stack limit.

Common mistakes

  • Returning the max distance from Pass 1 alone: Pass 1 only measures how far nodes are from node 0, which undercounts whenever the longest path passes through 0 (like 1 - 0 - 2) or bypasses 0's side branch completely.
  • Counting nodes instead of edges: A path visiting 5 nodes (1 - 2 - 3 - 4 - 5) crosses 4 edges; initializing dist[start_node] = 1 instead of 0 makes every answer off by 1.
  • Using recursion for DFS on large trees in Python: Python limits call-stack depth to 1,000 by default, so a recursive depth-first search crashes with RecursionError on a chain of 100,000 nodes.
  • Adding edges in only one direction (adj[u].append(v) without adj[v].append(u)): Input edges like [3, 0] have no fixed orientation; omitting the reverse direction traps BFS whenever an edge is listed "pointing toward" the start node.
  • Using queue.pop(0) on a plain Python list: Popping index 0 from a list shifts every remaining item left in O(n) time, quietly degrading a star-like BFS into O(n^2). Always use collections.deque.popleft().

Alternative approaches

  • Single-pass bottom-up tree DP (subtree heights): Root the tree arbitrarily at node 0. Every simple path in a rooted tree has a single highest node (its peak), where the path climbs up one child's subtree (all descendants below that child) and goes down another child's subtree. If we visit nodes in reverse BFS order (bottom-up from leaves to root, staying completely iterative) and compute height[u] = longest downward chain starting at u, then at each node u the longest path peaking at u combines its two largest values of height[child] + 1. This also runs in O(n) time and O(n) space, and unlike the two-BFS trick it still works even if edges can have negative weights!

Follow-up questions

  • How would you modify the traversal to return the sequence of nodes along a longest path instead of just its edge count? During Pass 2 (starting from end_a), keep a parent = [-1] * n list and set parent[neighbor] = curr whenever dist[neighbor] == -1. Once Pass 2 finishes at end_b, follow curr = parent[curr] backward from end_b until -1 and reverse the collected list to get [end_a, ..., end_b] in O(n) time and space.
  • Does the two-pass approach still hold when edges carry positive weights, and what changes if weights can be negative? Yes for positive weights! Because a tree has only one simple path between any two nodes, you do not even need Dijkstra's algorithm (a priority-queue shortest-path search for general graphs) — a plain iterative BFS or stack-based DFS accumulating dist[neighbor] = dist[curr] + weight computes exact distances in O(n) time, and the two-pass proof still holds whenever all edge weights are >= 0. If edges can have negative weights, however, the farthest-node lemma breaks and you should use the bottom-up two-largest-heights DP instead.
  • How can you locate the center node(s) of the tree that minimize its rooted height? Reconstruct any diameter path path of D edges (D + 1 nodes) using a parent array from Pass 2. If D is even, the single middle node path[D // 2] is the unique center (giving minimum possible height D // 2); if D is odd, the two middle nodes path[D // 2] and path[D // 2 + 1] tie as centers (giving minimum possible height (D + 1) // 2).

Follow-up questions

Similar questions

More Qualcomm interview questions

All 4 Qualcomm questions →