Process Restricted Friend Requests

Solution Code
# Union-find template
class UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.size = [1] * n
        self.n = n
        self.setCount = n
    
    def findset(self, x: int) -> int:
        if self.parent[x] == x:
            return x
        self.parent[x] = self.findset(self.parent[x])
        return self.parent[x]
    
    def unite(self, x: int, y: int) -> bool:
        x, y = self.findset(x), self.findset(y)
        if x == y: return False
        if self.size[x] < self.size[y]: x, y = y, x
        self.parent[y] = x
        self.size[x] += self.size[y]
        self.setCount -= 1
        return True
    
    def connected(self, x: int, y: int) -> bool:
        return self.findset(x) == self.findset(y)

class Solution:
    def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
        uf = UnionFind(n)
        result = []
        for u, v in requests:
            root_u, root_v = uf.findset(u), uf.findset(v)
            if root_u == root_v:
                result.append(True)
                continue
            can_be_friends = True
            for x, y in restrictions:
                root_x, root_y = uf.findset(x), uf.findset(y)
                if (root_u == root_x and root_v == root_y) or (root_u == root_y and root_v == root_x):
                    can_be_friends = False
                    break
            if can_be_friends:
                uf.unite(u, v)
                result.append(True)
            else:
                result.append(False)
        return result

Time Complexity

O(n + q * m * alpha(n)

Space Complexity

O(n)