Blind 75
46 / 75Free practice

Graph Valid Tree

Medium · Graphs

On LeetCode, Graph Valid Tree needs LeetCode Premium (checked October 2026). Here it is free: run and submit in Python, JavaScript, Java or C++ with a free account.

Jump to code

Given n ≥ 1 vertices labeled 0 through n−1 and undirected edges without self-loops or duplicate edges, decide whether the graph is one tree.

Examples

Example 1

n = 5
edges = [[0,1],[0,2],[0,3],[1,4]]

Output: true

Example 2

n = 5
edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]

Output: false

Constraints

  • 1 <= n <= 100
  • 0 <= edges.length <= n * (n - 1) / 2
Need a hint?

A tree is connected and has exactly n−1 edges.

Real graph interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  5,
  [
    [
      0,
      1
    ],
    [
      0,
      2
    ],
    [
      0,
      3
    ],
    [
      1,
      4
    ]
  ]
]
Expected
true
Case 2
Input
[
  5,
  [
    [
      0,
      1
    ],
    [
      1,
      2
    ],
    [
      2,
      3
    ],
    [
      1,
      3
    ],
    [
      1,
      4
    ]
  ]
]
Expected
false
Case 3
Input
[
  1,
  []
]
Expected
true
Case 4
Input
[
  4,
  [
    [
      0,
      1
    ],
    [
      1,
      2
    ],
    [
      2,
      3
    ]
  ]
]
Expected
true
Case 5
Input
[
  4,
  [
    [
      0,
      1
    ],
    [
      2,
      3
    ]
  ]
]
Expected
false

Drafts are saved per language in this browser when storage is available.