Magicsheet logo

Graph Valid Tree

Medium
32.4%
Updated 6/1/2025

Graph Valid Tree

What is this problem about?

The Graph Valid Tree coding problem asks you to determine if a given undirected graph is a valid tree. You are given an integer nn (the number of nodes from 0 to n1n-1) and a 2D array of edges. For an undirected graph to be a valid tree, it must satisfy two specific mathematical and structural conditions: it must be fully connected, and it must contain absolutely no cycles.

Why is this asked in interviews?

Companies like Google, Microsoft, and Meta ask this Graph interview pattern to test your fundamental understanding of graph theory properties. It evaluates whether you know the definitive characteristics of a tree and whether you can implement basic cycle detection and connectivity checks using Depth-First Search (DFS), Breadth-First Search (BFS), or Union Find.

Algorithmic pattern used

There are two elegant ways to solve this:

  1. Graph Theory Shortcut: A valid tree with nn nodes must have exactly n1n - 1 edges. If the number of edges is not n1n - 1, return False immediately. If it is exactly n1n - 1, you only need to verify that the graph is fully connected (using BFS/DFS or Union Find). If it has n1n-1 edges and is connected, it mathematically cannot have cycles.
  2. Union Find: Iterate through the edges. For each edge (u, v), check if uu and vv are already in the same set. If they are, a cycle exists (return False). If not, union them. Finally, check if the number of connected components is exactly 1.

Example explanation

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

  1. Number of edges is 4. n1n - 1 is 51=45 - 1 = 4. Condition 1 passes.
  2. Use BFS starting at 0:
    • Visit 0. Neighbors: 1, 2, 3.
    • Visit 1. Neighbor: 4.
    • Visit 2, 3, 4.
  3. Total nodes visited = 5.
  4. Since 5 nodes were visited, the graph is fully connected. Result: True (it is a valid tree).

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

  1. Number of edges is 5. 5eq515 eq 5 - 1. Result: False (too many edges, must contain a cycle).

Common mistakes candidates make

  • Ignoring Disconnected Components: Checking for cycles but forgetting to ensure that all nodes are reachable from a single starting point.
  • Undirected Cycle Detection in DFS: When doing a DFS to find cycles, failing to pass the parent node in the recursive call. In an undirected graph, visiting the node you just came from does not constitute a cycle.
  • Over-engineering: Using complex cycle detection without doing the simple edges==n1edges == n - 1 check first, which acts as a powerful O(1) filter.

Interview preparation tip

Memorize the definition of a tree in graph theory: "An undirected graph is a tree if and only if it is connected and has exactly V1V - 1 edges." This single sentence makes solving this problem trivial.

Similar Questions