Graph Theory37 sections · 1633 units
Open in Course

The Problem with Naive DSU

Long Chains

Imagine you merge 121-2, then 232-3, then 343-4. Up to nn. You might end up with a long chain: 123n1 \to 2 \to 3 \to \cdots \to n.

If you call find(1), you walk n1n-1 steps. That is O(n)O(n) per operation. For mm operations, total time is O(mn)O(mn). This is too slow when nn and mm are large.

Two optimizations fix this: path compression and union by size/rank. Together they make DSU nearly O(1)O(1) per operation.

Space complexity is O(n)O(n) for the data structures used.