28 · Union-Find & Minimum Spanning Trees

#261 Graph Valid Tree

frequently reported atLinkedInGoogleAmazon

the problem

In plain words

You get n nodes labelled 0 to n − 1 and a list of undirected edges edges[i] = [a, b] (no self-loops, no edge listed twice). Return true if these edges form a valid tree — every node can reach every other node, and there is no cycle — otherwise false.

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

out true

Node 0 connects to 1, 2, 3, and 1 connects to 4: connected, no loop.

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

out false

1 → 2 → 3 → 1 is a cycle (and 5 edges is one too many for 5 nodes).

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • edges[i] = [a, b] with 0 ≤ a, b < n and a ≠ b
  • No repeated edges

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #684
      Redundant Connection
      Mediumin Union-Find & MST
    2. #323
      Number of Connected Components in an Undirected Graph
      Mediumin Union-Find & MSTLeetCode Premium
    3. #310
      Minimum Height Trees
      Mediumin Topo Sort