#2076

Process Restricted Friend Requests

Hard
Union-FindGraph TheoryUnion-FindGraph Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * α(n))
Space
O(1)
O(n)
💡

Intuition

Time O(m * α(n))Space O(n)

Using the Union-Find data structure allows us to efficiently manage and check the connected components of the network. This way, we can quickly determine if two people can become friends without violating restrictions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a Union-Find structure to manage friend groups.
  2. 2Step 2: Process each request, checking if adding the friendship would violate any restrictions.
  3. 3Step 3: If it doesn't violate, union the two people; if it does, mark the request as unsuccessful.
solution.py23 lines
1class UnionFind:
2    def __init__(self, n):
3        self.parent = list(range(n))
4    def find(self, x):
5        if self.parent[x] != x:
6            self.parent[x] = self.find(self.parent[x])
7        return self.parent[x]
8    def union(self, x, y):
9        rootX = self.find(x)
10        rootY = self.find(y)
11        if rootX != rootY:
12            self.parent[rootY] = rootX
13
14def processRequests(n, restrictions, requests):
15    uf = UnionFind(n)
16    result = [True] * len(requests)
17    for u, v in requests:
18        if any(uf.find(u) == uf.find(x) and uf.find(v) == uf.find(y) for x, y in restrictions):
19            result.append(False)
20        else:
21            uf.union(u, v)
22            result.append(True)
23    return result

Complexity note: The time complexity is O(m * α(n)), where m is the number of requests and α is the inverse Ackermann function, which grows very slowly. The space complexity is O(n) for the Union-Find structure.

  • 1Using Union-Find allows efficient management of friend connections.
  • 2Directly checking restrictions for each request is inefficient.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.