 All Problems
Graph Valid Tree
medium
depth-first search
breadth-first search
union find
graph
google
linkedin

You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates there is an undirected edge between nodes ai and bi in the graph.

Return true if the edges of the given graph make up a valid tree, and false otherwise.

A valid tree has exactly n-1 edges and all nodes are connected (no cycles).

Example 1:

Input:
5 4
0 1
0 2
0 3
1 4
Output: true

Example 2:

Input:
5 5
0 1
1 2
2 3
1 3
1 4
Output: false

Constraints:

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai != bi
  • No self-loops, no repeated edges

Input format: First line: n numEdges. Then numEdges lines with "a b".

Output format: true or false.

Run to check your code against the sample cases, or submit to run every case