InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Graph Valid Tree

medium Original ↗ 00:00

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 is another approach: 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 no edge joins two already-connected nodes and the result is a single component, it's a tree.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug