Leetcode-Union-Find Data Sturcture

Yunrui Li
2 min readJun 2, 2020

--

A Union-Find data structure also called Disjoint set data structure is to maintain a set of elements partitioned into a number of mutually disjoint(non-overlapping) subsets. So, no elements belong to more than one set.

Definition:

In Union-Find data structure, each subset represent a backwards tree with pointer from a node to its parent and nodes in the tree are elements of this subset [1].

Properties:

  • The Union-Find data structure that efficiently support two operations
  1. Find: Given a node u, to find root node of u.
  2. Union: Given two nodes u and v, to merge them together if they’re disjoint. Otherwise, return False, which means they’re connected already.
  • Check whether two elements are in the same set by find function in O(log(n)*)≃ O(1), amortized time complexity.
Time Complexity copied from[5]
Example of Union method copied from[5]

Applications:

  • connected component in Graph problem
  • detecting cycles in graph.
  • minimum spanning tree

Implementation with an example:

There’re a couple ways to implement Union-Find with corresponding different time complexity[2]:

  1. union-by-size, O(log(n))
  2. union-by-height, O(log(n))
  3. union-by-rank with path compression, O(log(n)*)≃ O(1) [4].

Note:

  • It’s relatively rare to be used in Leetcode problems and sometimes it could be replaced with DFS solution. However, it can solve problem more efficiently.
  • How to implement [3]? Please see my code in below leetcode problems.
  • In order to use union-find data structure to solve problem, we need to convert each node to index ranging from 0 to n-1(totally, n nodes in the graph)

The below problems related to Union-Find in leetcode:

  • 200. Number of Islands
  • 305. Number of Islands II
  • 721. Accounts Merge

Reference:

[1].https://www.cs.princeton.edu/courses/archive/spr03/cs423/download/disjoint_set.pdf

[2].http://web.eecs.utk.edu/~jplank/plank/classes/cs302/Notes/Disjoint/

[3].https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/

[4]. inverse Ackerman’s function, Chapter 2, The algorithm design manual, 2nd edition

https://github.com/aforarup/interview/blob/master/Data%20Structures%20and%20Algorithm/Algorithm%20Books/The%20Algorithm%20Design%20Manual%20by%20Steven%20S.%20Skiena.pdf

[5].https://www.youtube.com/watch?v=VJnUwsE4fWA&ab_channel=HuaHua

--

--

Yunrui Li
Yunrui Li

Written by Yunrui Li

I’m Taiwanese expat. I’v worked in Singapore as data scientist after graduation from Taiwan and currently I work in Amsterdam as machine learning engineer.

No responses yet