Problem
There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that
xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b
is friends with a. Also, person a is acquainted with a person b if a
is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
2 <= n <= 1001 <= logs.length <= 10^4logs[i].length == 30 <= timestampi <= 10^90 <= xi, yi <= n - 1xi != yi- All the values
timestampiare unique. - All the pairs
(xi, yi)occur at most one time in the input.
Solution
Method 1 - Union Find (Disjoint Set Union)
Sort the logs by timestamp, then use union-find to merge friend groups. The earliest time when all are connected is when the number of groups becomes 1.
Code
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(M log M + M α(N))where M = logs.length, N = n, and α is the inverse Ackermann function. - 🧺 Space complexity:
O(N)