Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Graph Valid Tree
Problem
You are given n nodes labelled 0 to n - 1 and a list of undirected edges, each a pair [u, v]. Decide whether these edges form a tree over all n nodes: the graph must be connected and contain no cycle.
- There are at most 3,000 nodes and at most 8,000 edges.
- No self-loops, and each unordered pair appears at most once.
Examples
n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[4,5]]→true. Five edges, all six nodes connected, no cycle.n = 6, edges = [[0,1],[1,2],[2,3],[3,1],[4,5]]→false. Nodes 1, 2, 3 form a triangle, and node 0's part is a separate piece from {4,5}.n = 5, edges = [[0,1],[2,3]]→false. No cycle, but node 4 is isolated and {0,1}, {2,3} are two more separate components.
Hints
- How many edges does a tree on
nnodes have? What can you conclude if the count is wrong? - Given the right number of edges, only one of "connected" and "acyclic" still needs to be checked. Why?
- Union-find: process each edge; if both endpoints already share a root, the edge closes a cycle. With exactly
n-1edges and no cycle, the graph is automatically connected.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.