Union-Find (UF) becomes one of the popular algorithms in the tech interview nowadays. As indicated by its name, UF contains two parts: union and find. The step of find is to find the root of the group; and the step of union is to unite two groups with different roots.
A common implementation of the find function uses a recursive searching process. The end condition is when the root is that same as the key, or roots[key] == key;
if roots[X] == X, roots[Y] == Y, and we need to connect them, then we just need to set roots[X] = Y. After this operation, all the elements with X as the root previously now points to Y as the root. So the group with root as X and group with root Y are united. (We can set roots[Y] = X as well, but now the connected group root is X).
The roots could becomes very flat in the searching process, so the find process is of almost O(1) time complexity; the union is also of O(1), so the overall speed of UF is quite fast.
One of the conditions for whether use UF is that: find the connected groups. Once notice this condition, then we can generally consider to use the UF method.
Comments
Post a Comment