Graph Valid Tree

MediumGraphs
Asked byLinkedInGoogleAmazonMicrosoft

Problem

Given n nodes labeled 0 to n-1 and a list of undirected edges, determine whether these edges form a valid tree — the graph must be fully connected and contain no cycles.

Examples

Example 1
Input:n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output:true
Example 2
Input:n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output:false
There's a cycle between nodes 1, 2 and 3.

Constraints

  • 1 <= n <= 2000

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Graphs pattern

A graph models relationships as nodes and edges, which can be directed or undirected, weighted or not. Most graph problems come down to choosing the right traversal — DFS, BFS, or union-find — for what you're trying to find.

Look for this pattern when

  • The problem involves connections between items (islands, courses with prerequisites, friend networks, grids).
  • You need the shortest path in an unweighted graph (BFS) or need to explore every reachable node (DFS).
  • You're asking "are these two things connected?" repeatedly (union-find).

Read the full Graphs guide →

Video walkthroughs

Original problem on LeetCode ↗

More Graphs problems