Problem Description
We are given n people (labeled from 0 to n - 1) and a list of friendship events, where each event is represented by a log entry [timestamp, x, y]. At the given timestamp, person x and person y become friends. Friendship is both symmetric and transitive (i.e., a friend of a friend is also considered a friend). The goal is to determine the earliest timestamp at which all n people are connected (acquainted) with each other. If it is never possible for everyone to be connected, return -1.
Key Insights
- Sort the logs by their timestamps so that events are processed in chronological order.
- Use the Union-Find (disjoint-set) data structure to efficiently merge friendship groups.
- Maintain a count of connected components; when this count reaches 1, everyone is connected.
- If after processing all events the count is greater than 1, return -1.
Space and Time Complexity
Time Complexity: O(M log M + M * α(n)) where M is the number of log entries and α is the Inverse Ackermann function (nearly constant in practice). Space Complexity: O(n) for storing parent and rank arrays in the Union-Find structure.
Solution
The solution starts by sorting the log entries based on the timestamp to simulate the passage of time. We then initialize a Union-Find data structure with n disjoint sets (one for each person). For each log entry (friendship event), we perform a union operation to merge the sets of the two people involved. After each union, we check if we have only one connected component (i.e., all people are connected). If so, the current timestamp is the earliest moment when everyone becomes friends. If no such moment is reached by the end of the logs, we return -1.