Problem Description
There are n people (labeled 0 to n-1) and initially no friendships. Some pairs of people are restricted so that they cannot become friends either directly or indirectly. You are given a list of friendship requests. Process these requests in order and form friendships only when doing so will not indirectly connect any restricted pair. Even if the two users are already connected (directly or indirectly) then the request is considered successful. Return a boolean array indicating the success of each request.
Key Insights
- Use the Union Find (Disjoint Set Union) data structure to efficiently manage connected components.
- For each friendship request, check if merging the two components would violate any restriction.
- To check a restriction, simulate the union by mapping both involved leaders (if they are being merged) to one common representative.
- Revert or skip the union if any restricted pair would become connected.
- The constraints are small (n, requests, restrictions up to 1000) so checking all restrictions per request is acceptable.
Space and Time Complexity
Time Complexity: O(R * M * α(n))
R = number of requests, M = number of restrictions, and α(n) is the inverse Ackermann function (almost constant).
Space Complexity: O(n) for the union-find parent array (plus additional space for restrictions and requests).
Solution
We maintain a union-find (DSU) structure where each node has a parent pointer. For each friend request between u and v:
- Find their leaders.
- If they are already in the same group, the request is automatically successful.
- Otherwise, simulate a merge by assuming both groups are merged. For each restriction [x, y]: - Compute the effective leader for x and y; if a leader equals either of the two merging leaders, treat it as the new common representative. - If the effective leaders for x and y become equal after simulation, accepting the request would violate the restriction.
- If no violation is found, perform the union and mark the request as successful.
- Otherwise, reject the request.
This simulation ensures that merging u and v will not indirectly connect any pair that is restricted.