Skip to content

Edges Form a Single Tree

Easy#union-find#cycle-detection~15 min

The mission

Problem

You are given n nodes labelled 0 to n - 1 and a list of undirected edges. Return whether the edges form exactly one tree: every node is connected to every other, and there is no cycle.

Examples

Input:  n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: True
Input:  n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: False
Why:    1, 2 and 3 form a cycle
Input:  n = 4, edges = [[0, 1], [2, 3]]
Output: False
Why:    edge case, no cycle, but the graph is in two pieces

Hints

0 / 3

Target time
O(n · α(n))
Target space
O(n)

Constraints

  • nodes are labelled 0 to n − 1

Stuck on the idea rather than the code? Components & Cycles covers it.

Python 3Ctrl+Enter runs
Custom test case