InterviewPrepKit

Home / Coding / Graphs

Graph Valid Tree πŸ”’

medium Original β†—
Solving tips
  • Recognize the tree identities: a tree on n nodes has exactly n-1 edges AND is connected; any two of {n-1 edges, connected, acyclic} imply the third.
  • Fast path: if len(edges) != n-1 return False immediately, then a single DFS/BFS from node 0 that reaches all n nodes proves it, all in O(V+E).
  • Union-find is the cleanest alternative: an edge whose endpoints already share a root closes a cycle, so return False; it needs no separate edge-count check.
  • Pitfall: n-1 edges alone is not sufficient (could be a cycle plus an isolated node) and you must add both directions for the undirected adjacency list.

Problem

You have n nodes labeled 0 to n - 1 and a list of undirected edges, each [u, v]. Return True if these edges form a valid tree, and False otherwise.

A graph is a tree exactly when it is connected (every node reachable from every other) and acyclic (no cycles). Equivalently, a tree on n nodes has exactly n - 1 edges and is connected β€” or, has n - 1 edges and no cycle. Either pair of conditions is sufficient.

Examples

  • n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] β†’ True β€” 4 edges = 5 βˆ’ 1, connected, no cycle. It’s a tree.
  • n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] β†’ False β€” 5 edges on 5 nodes; the extra edge [1,3] closes a cycle 1–2–3–1.
  • n = 4, edges = [[0,1],[2,3]] β†’ False β€” only 2 edges; the graph splits into two disconnected pieces.
  • n = 1, edges = [] β†’ True β€” a single node with no edges is a valid (trivial) tree.

Constraints

  • 1 <= n <= 2000
  • 0 <= len(edges) <= 5000
  • No self-loops and no duplicate edges in the input.

Think about it first

Hint 1 A tree on n nodes has exactly n βˆ’ 1 edges. If the count differs, you can answer immediately: fewer means disconnected, more means a cycle must exist. So first check len(edges) == n - 1.
Hint 2 Once the edge count is n βˆ’ 1, you only need to verify one more thing β€” connectivity (which, given n βˆ’ 1 edges, also rules out cycles). A single DFS/BFS from node 0 that reaches all n nodes proves it's a tree.
Hint 3 Union-find gives an elegant alternative: union the two endpoints of each edge; if an edge's endpoints are already in the same set, that edge creates a cycle β†’ not a tree. If you survive all edges with no such collision and end with a single component, it's a tree.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.