Skip to main content
47

Graph Valid Tree

Mediumgraphsunion find

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:GraphsRead the beginner guide

You're given n nodes labeled 0 to n - 1 and a list of undirected edges. Return true if these edges form a valid tree, and false otherwise.

Understand the problem

In graph terms, a tree is a graph that is both:

  1. connected: you can get from any node to any other by following edges, and
  2. acyclic: it has no cycles (no way to walk in a loop and come back to where you started without reusing an edge).

There's no root or left/right here: it's the general shape of a tree, just nodes and connections.

Example 1

text
Input:  n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true

      0
    / | \
   1  2  3
   |
   4

Everything is connected, and there are no loops.

Example 2

text
Input:  n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false

1 ─ 2 ─ 3 ─ 1 is a cycle.

Example 3

text
Input:  n = 4, edges = [[0, 1], [2, 3]]
Output: false

No cycles, but {0, 1} and {2, 3} aren't connected to each other.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • No repeated edges or self-loops.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    A tree with n nodes has exactly n - 1 edges; check that first, then add the edges with Union-Find and fail if any edge connects two nodes that are already connected (that edge would close a cycle).

    The key insight: a counting shortcut

    Try drawing trees with 1, 2, 3, 4 nodes. Each time you add a node to a tree, you connect it with exactly one new edge. So:

    A tree with n nodes has exactly n - 1 edges.

    • Fewer than n - 1 edges: there aren't enough to connect everything. Not a tree.
    • More than n - 1: there's at least one extra edge, which must close a cycle. Not a tree.
    • Exactly n - 1: then "connected" and "no cycle" go together: if one is true, so is the other. So you only need to check one of them.

    Checking for a cycle with Union-Find

    Union-Find keeps track of which nodes are already connected, in groups (see Number of Connected Components). Add the edges one at a time:

    • If the edge's two ends are in different groups, merge the groups.
    • If they're already in the same group, there was already a path between them. Adding this edge creates a second path: that's a cycle. Return false.

    If every edge merges two different groups, there's no cycle, and with n - 1 edges, the graph is a tree.

    Step by step

    n = 4, edges = [[0, 1], [1, 2], [2, 0]]: exactly n - 1 = 3 edges, so the count check passes.

    EdgeGroups beforeSame group?Action
    [0, 1]{0} {1} {2} {3}nomerge → {0,1} {2} {3}
    [1, 2]{0,1} {2} {3}nomerge → {0,1,2} {3}
    [2, 0]{0,1,2} {3}yescycle! → false

    Notice node 3 is also disconnected: the cycle "used up" an edge that should have connected it. That's why checking only one property is enough.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With V nodes and E edges:

    • Time: about O(V + E). Each find is nearly constant thanks to path compression.
    • Memory: O(V) for the parent array.

    Common mistakes

    • Only checking for cycles. Example 3 has no cycle, but isn't connected. The edge count check catches it.
    • Only checking connectivity with more than n - 1 edges: everything can be connected and still contain a cycle.
    • Forgetting n = 1 with no edges. A single node is a valid tree: 0 edges = n - 1.

    Going deeper

    • DFS works too: after the edge count check, run a search from node 0 and count how many nodes you reach. It's a tree exactly when you reach all n.
    • The same "an edge inside one group closes a cycle" idea finds the redundant connection in a graph, and it's the heart of Kruskal's algorithm for building a minimum spanning tree.

    Reference solution

    js
    /**
     * @param {number} n
     * @param {number[][]} edges
     * @return {boolean}
     */
    export default function validTree(n, edges) {
      // A tree with n nodes has exactly n - 1 edges. With exactly that many,
      // "no cycle" also guarantees "connected", so we only need to look for a cycle.
      if (edges.length !== n - 1) return false
      // Union-Find: every node starts as its own group, pointing to itself.
      const parent = Array.from({ length: n }, (_, i) => i)
      // Follow parent pointers up to the group's representative.
      function find(x) {
        while (parent[x] !== x) {
          parent[x] = parent[parent[x]] // path compression: skip a level for next time
          x = parent[x]
        }
        return x
      }
    
      for (const [a, b] of edges) {
        const rootA = find(a)
        const rootB = find(b)
        // Already connected some other way: this edge would close a cycle.
        if (rootA === rootB) return false
        parent[rootA] = rootB // merge the two groups
      }
      return true
    }
    ts
    export default function validTree(n: number, edges: number[][]): boolean {
      // A tree with n nodes has exactly n - 1 edges. With exactly that many,
      // "no cycle" also guarantees "connected", so we only need to look for a cycle.
      if (edges.length !== n - 1) return false
      // Union-Find: every node starts as its own group, pointing to itself.
      const parent = Array.from({ length: n }, (_, i) => i)
      // Follow parent pointers up to the group's representative.
      function find(x: number): number {
        while (parent[x] !== x) {
          parent[x] = parent[parent[x]] // path compression: skip a level for next time
          x = parent[x]
        }
        return x
      }
    
      for (const [a, b] of edges) {
        const rootA = find(a)
        const rootB = find(b)
        // Already connected some other way: this edge would close a cycle.
        if (rootA === rootB) return false
        parent[rootA] = rootB // merge the two groups
      }
      return true
    }
    python
    def valid_tree(n: int, edges: list[list[int]]) -> bool:
        # A tree with n nodes has exactly n - 1 edges. With exactly that many,
        # "no cycle" also guarantees "connected", so we only need to look for a cycle.
        if len(edges) != n - 1:
            return False
        # Union-Find: every node starts as its own group, pointing to itself.
        parent = list(range(n))
    
        # Follow parent pointers up to the group's representative.
        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]  # path compression: skip a level for next time
                x = parent[x]
            return x
    
        for a, b in edges:
            root_a, root_b = find(a), find(b)
            # Already connected some other way: this edge would close a cycle.
            if root_a == root_b:
                return False
            parent[root_a] = root_b  # merge the two groups
        return True