Skip to content
Decoder

Graph Valid Tree

Medium

Problem

You have n nodes labelled 0 to n - 1 and a list of undirected edges. Return true if these edges make a valid tree: every node is connected to every other, and there are no cycles.

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
Why
1-2-3 is a cycle

Example 3

Input
n = 4, edges = [[0, 1], [2, 3]]
Output
false
Why
two pieces

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • No self-loops and no repeated edges

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.