Earliest Time Everyone Is Connected
GoogleOnsiteMedium
n people are labeled 0 to n - 1. A log entry [timestamp, a, b, action] says that at timestamp, people a and b become friends (action == 1) or stop being friends (action == 0). Entries are not sorted and all timestamps are distinct. Every entry is valid: a befriend entry joins two people who are not friends, and an unfriend entry separates two people who are. Entries take effect in increasing timestamp order.
Two people are acquainted if they are friends or connected through a chain of friends. Implement earliest_connected(n, logs), which returns the smallest timestamp at which everyone is acquainted with everyone else, or -1 if that never happens.
Part 1: Befriend events only
In this part every entry has action == 1, so friendships are only added, never removed. Return the earliest timestamp at which all n people are acquainted with each other, or -1 if that never happens.
- Example 1
- n
4- logs
[[20,2,3,1],[5,0,1,1],[12,1,2,1],[30,0,3,1]]- Output
20
Why: In time order: 0-1 at 5, 1-2 at 12, 2-3 at 20. After time 20 all four people are in one group, so the answer is 20; the later event at 30 does not matter.
Constraints
2 <= n <= 10001 <= len(logs) <= 20000 <= a, b < nanda != b1 <= timestamp <= 10^9, all timestamps distinctaction == 1in every entry