Union-find keeps track of which nodes are in the same group. Every node 0 .. n-1 points at one node, its parent, and following the arrows always leads up to a node that points at itself: the root. Each group has one root, so two nodes are in the same group exactly when their arrows lead to the same root.
All of it is stored in one list: parent[x] is the node that x points at.
Write find_roots(parent: list[int]) -> list[int] that returns, for every node, the root its arrows lead to.
find_roots([0, 0, 1, 3, 3]) # [0, 0, 0, 3, 3]
Nodes 0 and 3 point at themselves, so they are the roots. Node 1 points at 0. Node 2 points at 1, which points at 0, so node 2's root is 0 too. Node 4 points at 3. That makes two groups: {0, 1, 2} with root 0, and {3, 4} with root 3.
find_roots([1, 2, 2]) # [2, 2, 2] 0 -> 1 -> 2, and 2 points at itself
find_roots([]) # []
0 <= len(parent) <= 2 * 10^5. The arrows never go round in a loop (apart from a root pointing at itself), so following them from any node always reaches a root.- You may change
parentwhile you work. - ⭐ Bonus: a speed test with one long chain of 200,000 nodes earns a star if you don't walk the whole chain again for every node.
Show hint
find(x) is a loop: while parent[x] != x, move x up to parent[x]. For the ⭐, once you know the root, walk the same path a second time and point every node on it straight at the root ("path compression"), so later walks are short.