Skip to content

Graph Valid Tree

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

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.

n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]          →  true
n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]  →  false   (1-2-3 is a cycle)
n = 4, edges = [[0, 1], [2, 3]]                          →  false   (two pieces)

Constraints

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