Count the connected components of an undirected graph with union-find
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Start with every node in its own group, so the count is n. Each edge that joins two different groups merges them and lowers the count by one; an edge inside one group changes nothing.
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.