Some bad ideas for implementing union-find [00P5]

How can we implement a union-find data structure? One simple idea is to just keep a dictionary that maps each item to an "id" which identifies which set it is in.

  • \mathsf {Find} takes \Theta (1), assuming we can do \Theta (1) dictionary lookup (e.g. using a hash table).
  • To do \mathsf {Union}, however, we have to go through every single item to find which ones are in the set we want to change, and change them all to the other set. This takes \Theta (n), which is too slow.

We could also try to flip things around and keep a dictionary mapping each set id to a list of items in that set.

  • \mathsf {Union} is now \Theta (1) (assuming we use something like linked lists), since we can just append one list to the other.
  • However, \mathsf {Find} is now \Theta (n): to find an item we simply have to go through every list looking for it.

Can we somehow get the best of both worlds?