Chat app~25 min2s · 256 MBtarget O(m log m + m α(n)) time, O(n) spaceclassic twin: lc-1101union-find
A chat app records every time two users add each other as contacts. A group is a set of users who can reach one another through a chain of contacts. The log lists the events in any order.
The product team wants to know when a group first becomes big enough to deserve a shared channel. They ask for the earliest time at which some group has at least k users.
Write earliest_group_of(users, logs, k).
users is the number of users, numbered 0 to users - 1. At the start nobody is linked, so every user is a group of one.logs[i] is [time, a, b]: at that time, users a and b became contacts. The logs are not sorted, and several logs can have the same time.k users. Return -1 when no group ever does.Input: users = 6, logs = [[7,0,1],[3,2,3],[9,1,2],[5,4,5],[2,0,2]], k = 4
Output: 7The solution sorts the logs by time, then joins the groups one log at a time. After each join it checks the size of the new group.
| Log read | Group made | Size | At least 4 |
|---|---|---|---|
[2,0,2] |
0, 2 |
2 | no |
[3,2,3] |
0, 2, 3 |
3 | no |
[5,4,5] |
4, 5 |
2 | no |
[7,0,1] |
0, 1, 2, 3 |
4 | yes |
The group first reaches 4 users at time 7.
Input: users = 6, logs = [[7,0,1],[3,2,3],[9,1,2],[5,4,5],[2,0,2]], k = 2
Output: 2The earliest log already makes a group of two.
Input: users = 6, logs = [[7,0,1],[3,2,3],[9,1,2],[5,4,5],[2,0,2]], k = 6
Output: -1The largest group ever has 4 users. The log at time 9 joins users who are already together.
2 ≤ users ≤ 100,000 and 2 ≤ k ≤ users0 ≤ len(logs) ≤ 100,000, and every log is [time, a, b] with 0 ≤ time ≤ 1,000,000,000 and 0 ≤ a, b < usersRebuilding the groups for each distinct time costs about 100,000 logs for each of 100,000 times, which is 10,000,000,000 steps. The groups only grow as time passes, so one pass in time order can keep them up to date.