Skip to content
BytePatterns

Edges Form a Single Tree

EasyUnion-Find#union-find#cycle-detection~15m

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

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