Graph Valid Tree
Given n nodes and edges array where each [a, b] is an undirected edge Return True if graph is a valid tree (connected, acyclic, n-1 edges) Example: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] => True Example: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] => False (cycle)
You're checking whether a set of connections forms a proper tree—one connected piece with no loops. It's a favorite in interviews because it forces you to articulate what makes a tree a tree, then verify those properties cleanly. The classic gotcha is accidentally detecting cycles when you revisit your parent node. Once you're comfortable here, connected-component problems become much easier.
Examples
You write
valid_tree(n: int, edges: List[List[int]])
Example 1
- Input
- n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
- returns
- true
Example 2
- Input
- n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
- returns
- false
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.