Graph Valid Tree

35 min · validTree()

A network can reach every machine and still be wrong: one extra cable may create a loop. A tree allows neither gaps nor loops.

You're given n nodes labeled from 0 through n - 1. Each pair [a, b] is an undirected edge, meaning you can travel between a and b in either direction. Return true only when all the edges together form a valid tree.

That requires both conditions:

  • Every node is reachable from every other node.
  • There is no cycle — a route that leaves a node and returns to it without reusing an edge.

A single node with no edges is a valid tree.

Constraints

  • 1 <= n <= 2_000
  • 0 <= edges.length <= 5_000
  • Every edge contains two node labels in the range 0..n - 1.
  • There are no self-loops and no duplicate undirected edges.

Hints

Count before you explore

A tree on n nodes always has exactly n - 1 edges. That count can reject many inputs immediately, but it can't prove that the remaining edges are connected.

Watch each merge

Start with every node in its own group. An edge should merge two different groups. What does it mean if both endpoints are already in the same group?

Finish the proof

Union-find catches a cycle as soon as an edge joins an existing group to itself. After every edge, check that only one group remains.

Follow-up

Suppose the edges arrive one at a time. Can you reject the first edge that makes a tree impossible without rebuilding the graph after every arrival?

Visible cases

Examples

Example 1

ready
Input
n = 5
edges = [
  [
    0,
    1
  ],
  [
    0,
    2
  ],
  [
    0,
    3
  ],
  [
    1,
    4
  ]
]
Expected
true
Why
four edges connect all five nodes without a loop

Example 2

ready
Input
n = 5
edges = [
  [
    0,
    1
  ],
  [
    1,
    2
  ],
  [
    2,
    3
  ],
  [
    1,
    3
  ],
  [
    1,
    4
  ]
]
Expected
false
Why
1 → 2 → 3 → 1 forms a cycle

Example 3

ready
Input
n = 1
edges = []
Expected
true
Why
one isolated node is already a tree

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite