Graph Valid Tree

MediumGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given n nodes labeled 0 to n - 1 and a list edges, where each edges[i] = [a, b] is an **undirected** edge between nodes a and b. Return true if these edges form a single valid tree over all n nodes, and false otherwise. A valid tree is connected (every node can reach every other node) and contains no cycles. The edge list has no self-loops and no repeated edges. A single node with no edges is a valid tree. Aim for near-linear time in n + edges.length.

Examples

Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
All five nodes are connected and there are exactly 4 edges with no cycle.
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Nodes 1, 2 and 3 form a cycle.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2
  • 0 <= a, b < n and a != b
  • No edge appears twice

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems