graph-valid-tree.sh — zsh
graphdfsbfsunion-find

You have a graph of n nodes labeled from 0 to n - 1 and a list of undirected edges, where edges[i] = [a_i, b_i] indicates an undirected edge between nodes a_i and b_i.

Return true if the edges make up a valid tree, and false otherwise.

Recall that an undirected graph on n vertices is a valid tree if and only if it is fully connected and contains no cycles (equivalently, it has exactly n - 1 edges and all n nodes belong to a single connected component).

Input / output

  • Input: n: int, edges: int[][]
  • Output: boolean

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2, 0 <= a_i, b_i < n, a_i != b_i
  • No duplicate undirected edges

Follow-up

Compare DFS/BFS traversal against Union-Find (Disjoint Set Union): which one lets you detect cycles incrementally if edges arrive as a stream?

Examples
Example 1
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Example 2: contains cycle
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Example 3: disconnected forest
Input: n = 4, edges = [[0,1],[2,3]]
Output: false