Count the connected components of an undirected graph with union-find

mediumAbout 25 minutesUpdated CodingPrographsunion-find
Not solved

Share this question

Problem

A design system's components reference each other; a social graph links users; a spreadsheet's cells depend on one another. "How many separate groups are there?" is the same question each time. Nodes are numbered 0 to n - 1, and edges is a list of [a, b] pairs, each an undirected link.

countComponents(5, [[0, 1], [1, 2], [3, 4]]);  // 2
groupComponents(5, [[0, 1], [1, 2], [3, 4]]);  // [[0, 1, 2], [3, 4]]
countComponents(3, []);                        // 3 (every node alone)

Ref. UR-1425 · © UIRound · uiround.com/questions/count-the-connected-components-of-an-undirected-graph-with-union-find

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment