Graph Valid Tree

Check if an undirected graph is a valid tree.

Pattern

Union-Find / DFS

This problem follows the Union-Find / DFS pattern, commonly found in the Graphs category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

A valid tree has n-1 edges and is connected. Use union-find to check for cycles.

Key Insight

Two conditions define a tree: n-1 edges (no extra) and connected (no missing). Union-Find checks both: edge count + no cycles = tree.

Step-by-step

  1. 1A tree with n nodes must have exactly n-1 edges
  2. 2The graph must be connected (all nodes reachable)
  3. 3Use Union-Find: for each edge, union the two nodes
  4. 4If an edge connects two nodes already in the same set, it's a cycle

Pseudocode

if len(edges) != n - 1: return false
parent = list(range(n))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
def union(x, y):
    px, py = find(x), find(y)
    if px == py: return false  # cycle
    parent[px] = py
    return true
return all(union(a, b) for a, b in edges)
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Graphs Problems

Master this pattern with YeetCode

Practice Graph Valid Tree and similar Graphs problems with flashcards. Build pattern recognition through active recall.

Practice this problem