Skip to content

Commit 8bc48d1

Browse files
authored
Create process-restricted-friend-requests.py
1 parent bd9b6f7 commit 8bc48d1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Time: O(n * (alpha(n) + r)) = O(n * r)
2+
# Space: O(n)
3+
4+
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
5+
def __init__(self, n):
6+
self.set = range(n)
7+
self.rank = [0]*n
8+
9+
def find_set(self, x):
10+
stk = []
11+
while self.set[x] != x: # path compression
12+
stk.append(x)
13+
x = self.set[x]
14+
while stk:
15+
self.set[stk.pop()] = x
16+
return x
17+
18+
def union_set(self, x, y):
19+
x, y = self.find_set(x), self.find_set(y)
20+
if x == y:
21+
return False
22+
if self.rank[x] > self.rank[y]: # union by rank
23+
x, y = y, x
24+
self.set[x] = self.set[y]
25+
if self.rank[x] == self.rank[y]:
26+
self.rank[y] += 1
27+
return True
28+
29+
30+
class Solution(object):
31+
def friendRequests(self, n, restrictions, requests):
32+
"""
33+
:type n: int
34+
:type restrictions: List[List[int]]
35+
:type requests: List[List[int]]
36+
:rtype: List[bool]
37+
"""
38+
result = []
39+
uf = UnionFind(n)
40+
for u, v in requests:
41+
pu, pv = uf.find_set(u), uf.find_set(v)
42+
ok = True
43+
for x, y in restrictions:
44+
px, py = uf.find_set(x), uf.find_set(y)
45+
if {px, py} == {pu, pv}:
46+
ok = False
47+
break
48+
result.append(ok)
49+
if ok:
50+
uf.union_set(u, v)
51+
return result

0 commit comments

Comments
 (0)