Friend Circle Queries

  • + 0 comments

    python solution:

    class UnionFind:
        """
        Optimized Union-Find (Disjoint Set) data structure with path compression
        and union by rank optimizations.
        """
        def __init__(self):
            self.parent = {}
            self.rank = {}
            self.size = {}
            
        def make_set(self, x: int) -> None:
            if x not in self.parent:
                self.parent[x] = x
                self.rank[x] = 0
                self.size[x] = 1
                
        def find(self, x: int) -> int:
            """Find with path compression"""
            if x != self.parent[x]:
                self.parent[x] = self.find(self.parent[x])
            return self.parent[x]
            
        def union(self, x: int, y: int) -> int:
            """Union by rank with size tracking"""
            px, py = self.find(x), self.find(y)
            
            if px == py:
                return self.size[px]
                
            if self.rank[px] < self.rank[py]:
                px, py = py, px
            
            self.parent[py] = px
            self.size[px] += self.size[py]
            
            if self.rank[px] == self.rank[py]:
                self.rank[px] += 1
                
            return self.size[px]
    
    def maxCircle(queries):
        uf = UnionFind()
        max_size = 0
        result = []
        
        for x, y in queries:
            # Create sets if they don't exist
            uf.make_set(x)
            uf.make_set(y)
            
            # Perform union and get size of resulting set
            current_size = uf.union(x, y)
            max_size = max(max_size, current_size)
            result.append(max_size)
            
        return result