Imagine you're managing a social network where people can send friend requests, but some pairs of users are forbidden from being connected - either directly or indirectly through mutual friends!
You have n people labeled from 0 to n-1, initially with no friendships. You're given:
- Restrictions: A list of pairs
[xi, yi]who cannot be friends (directly or through a chain of mutual friends) - Friend Requests: A sequence of requests
[uj, vj]processed in order
Your goal is to determine which friend requests can be approved without violating any restrictions. Each successful request creates a permanent friendship that affects all future requests.
Key Challenge: When two people become friends, their entire friend groups merge! You must ensure that no restricted pairs end up in the same connected group.
Input & Output
Visualization
Time & Space Complexity
For m requests, each requires checking r restrictions plus Union-Find operations with inverse Ackermann time complexity
Union-Find parent and rank arrays
Constraints
- 2 โค n โค 1000
- 0 โค restrictions.length โค 1000
- restrictions[i].length == 2
- 0 โค xi, yi โค n - 1
- xi โ yi
- 1 โค requests.length โค 1000
- requests[j].length == 2
- 0 โค uj, vj โค n - 1
- uj โ vj
- All restrictions and requests contain distinct pairs