![]() |
VOOZH | about |
You have a network of individuals, each labeled with a number from 0 to n - 1. Some individuals cannot be friends due to specific rules. You also have a list of friend requests, processed one by one, the task is to determine whether each request can be accepted based on the established regulations. For each request, you need to tell the person u and v can be friends or not. If they are friends then they become friends for all future requests.
Examples:
Input: n = 3, restrictions[][] = [[0,1]], requests[][] = [[0, 2], [2, 1]]
Output: [true, false]
Explanation: Initially, no one is friends with each other.
Request 0: Person 0 and person 2 can be friends, so they become direct friends. (0--2)
Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).Input: n = 5, restrictions[][] = [[0, 1], [1, 2], [2, 3]], requests[][] = [[0, 4], [1, 2], [3, 1], [3, 4]]
Output: [true, false, true, false]
Explanation: Initially, no one is friends with each other.
Request 0: Person 0 and person 4 can be friends, so they become direct friends. (0--4)
Request 1: Person 1 and person 2 cannot be friends since they are directly restricted. (1 and 2 have restrictions)
Request 2: Person 3 and Person 1 can be friends, so they become direct friends. (3--1)
Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).
We can solve this problem Using Disjoint-Set-Union Concept .
This code effectively processes friend requests in a network while considering restrictions and ensures that friends are connected through a disjoint-set data structure with path compression for efficient operations.
Below is the implementation of the above Approach:
[True,False,True,False,]
Time Complexity: O(n+m*log(n) + r*m)
Auxiliary Space: O(n)