call(back)
Algorithms & Data StructureseasySign in to star problems

Sensor Network I

Field sensors numbered 0 to n − 1 are linked by undirected edges (u, v). Return whether the network contains a cycle.

n = 5, edges = [[0, 1], [1, 2], [2, 0]]   ->  true    (a triangle)
n = 4, edges = [[0, 1], [2, 3]]           ->  false

A self-loop, or the same link listed twice, counts as a cycle.

Hints

Hint 1

Union-Find: process the edges one at a time. If both endpoints already have the same root, this edge closes a cycle.

Hint 2

DFS works too, as long as you ignore the edge you arrived by — but a duplicate link then needs care, which Union-Find handles for free.

Asked at