Given n nodes labeled from 0 to n-1 and a list of undirected edges, determine if these edges form a valid tree.

A valid tree is a connected graph with exactly n-1 edges and no cycles. Think of it like a family tree or organizational chart - every node should be reachable from every other node, but there should be exactly one path between any two nodes.

Key Properties of a Tree:

  • ๐ŸŒณ Connected: All nodes must be reachable
  • ๐Ÿšซ Acyclic: No cycles allowed
  • ๐Ÿ“ Minimal: Exactly n-1 edges (not more, not less)

Return true if the edges form a valid tree, false otherwise.

Input & Output

example_1.py โ€” Valid Tree
$ Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,4]]
โ€บ Output: true
๐Ÿ’ก Note: This forms a valid tree: 5 nodes with 4 edges, fully connected with no cycles. Node 1 acts as a hub connecting to nodes 0, 2, and 4, with node 3 connected through node 2.
example_2.py โ€” Has Cycle
$ Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,4],[3,4]]
โ€บ Output: false
๐Ÿ’ก Note: This graph contains a cycle: 1โ†’2โ†’3โ†’4โ†’1. A valid tree cannot have cycles, so this returns false even though all nodes are connected.
example_3.py โ€” Disconnected Components
$ Input: n = 4, edges = [[0,1],[2,3]]
โ€บ Output: false
๐Ÿ’ก Note: This graph has two disconnected components: {0,1} and {2,3}. A valid tree must be fully connected, so this returns false.

Visualization

Tap to expand
Valid Tree Propertiesโœ“ VALID TREE0123 nodes, 2 edgesโœ— HAS CYCLE0123 nodes, 3 edgesโœ— DISCONNECTED0123 nodes, 1 edgeAlgorithm Steps1. Check Edge Count:if (edges.length != n - 1) return false2. Build Graph & DFS:Build adjacency list, then traverse with DFSTrack visited nodes and parent to detect cycles3. Verify Connectivity:Ensure all n nodes were visited in traversalIf yes โ†’ Valid Tree, If no โ†’ Disconnected
Understanding the Visualization
1
Edge Count Check
A tree with n nodes must have exactly n-1 edges
2
Cycle Detection
Use DFS or Union-Find to detect if any cycles exist
3
Connectivity Check
Verify all nodes are reachable from any starting node
Key Takeaway
๐ŸŽฏ Key Insight: A valid tree is the minimal connected graph - exactly n-1 edges with full connectivity and zero cycles!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n + m)

We visit each node once and examine each edge once, where n is nodes and m is edges

n
2n
โœ“ Linear Growth
Space Complexity
O(n + m)

Space for adjacency list (O(n + m)) plus visited set (O(n)) plus recursion stack (O(n) in worst case)

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 2000
  • 0 โ‰ค edges.length โ‰ค 5000
  • edges[i].length == 2
  • 0 โ‰ค ai, bi < n
  • ai โ‰  bi
  • No duplicate edges in the input
Asked in
Google 42 Facebook 38 Amazon 31 Microsoft 25
67.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen