clean python union find with path compression

  • 0

    All credit goes to this guy for awesome explanation.

    class Solution(object):
        def countComponents(self, n, edges):
            ds = DisjointSet()
            for i in range(n):
            for i, j in edges:
                ds.union(i, j)
            return ds.num_sets
    class Node(object):
        def __init__(self, data, parent=None, rank=0):
   = data
            self.parent = parent
            self.rank = rank
    class DisjointSet(object):
        def __init__(self):
   = {}
            self.num_sets = 0
        def make_set(self, data):
            node = Node(data)
            node.parent = node
  [data] = node
            self.num_sets += 1
        def union(self, data1, data2):
            node1 =[data1]
            node2 =[data2]
            parent1 = self.find_set_util(node1)
            parent2 = self.find_set_util(node2)
            if ==
            if parent1.rank >= parent2.rank:
                if parent1.rank == parent2.rank:
                    parent1.rank += 1
                parent2.parent = parent1
                parent1.parent = parent2
            self.num_sets -= 1
        def find_set(self, data):
            return self.find_set_util([data])
        def find_set_util(self, node):
            parent = node.parent
            if parent == node:
                return parent
            node.parent = self.find_set_util(node.parent)
            return node.parent

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.