Graph Valid Tree

MediumGraphs

You get n nodes, numbered 0 to n - 1, and a list of undirected edges, where [a, b] joins node a and node b.

Return true if these edges make a tree: every node is connected to every other, and there is no cycle. Return false otherwise.

Examples

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

Every node hangs off 0 or 2, all five are connected, and nothing loops.

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

Nodes 0, 1 and 2 form a loop.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • 0 ≤ a, b < n and a ≠ b
  • No edge appears twice.

Stuck?

Hint 1

A tree on n nodes has exactly n - 1 edges. With that many edges, having no cycle and being connected come to the same thing.

Hint 2

Check the edge count first. Then add the edges to a union-find one by one: an edge whose two ends already share a root closes a cycle.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur