-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathProcess Restricted Friend Requests.java
64 lines (59 loc) · 2.12 KB
/
Process Restricted Friend Requests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
int[] parent;
boolean[] result;
public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
result = new boolean[requests.length];
for (int i = 0; i < requests.length; i++) {
// personA and personB can become friends if for all restrictions
// person x_i and person y_i are not in the same set as personA and personB
// and vice versa
int personA = requests[i][0];
int personB = requests[i][1];
int personASetRepresentative = find(personA);
int personBSetRepresentative = find(personB);
boolean flag = true;
for (int[] restriction : restrictions) {
int blackListPersonARepresentative = find(restriction[0]);
int blackListPersonBRepresentative = find(restriction[1]);
if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) {
flag = false;
}
if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) {
flag = false;
}
}
if (flag) {
union(personA, personB);
}
result[i] = flag;
}
return result;
}
private int find(int node) {
int root = node;
while (parent[root] != root) {
root = parent[root];
}
//path compression
int curr = node;
while (parent[curr] != root) {
int next = parent[curr];
parent[curr] = root;
curr = next;
}
return root;
}
private boolean union(int node1, int node2) {
int root1 = find(node1);
int root2 = find(node2);
if (root1 == root2) {
return false;
}
parent[root2] = root1;
return true;
}
}