The Earliest Moment When Everyone Become Friends - 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.
Input & Output
Example 1 — Basic Case
$
Input:
logs = [[20,0,1],[5,2,3],[15,3,4],[18,0,2]], n = 5
›
Output:
20
💡 Note:
At time 5: {2,3} connected. At time 15: {2,3,4} connected. At time 18: {0,2,3,4} connected. At time 20: {0,1,2,3,4} all connected - everyone knows everyone!
Example 2 — Already Connected
$
Input:
logs = [[0,1,0],[1,0,1]], n = 2
›
Output:
0
💡 Note:
At time 0, persons 0 and 1 become friends, so everyone is connected immediately
Example 3 — Impossible Case
$
Input:
logs = [[0,0,1],[2,1,2]], n = 4
›
Output:
-1
💡 Note:
Person 3 never gets connected to anyone, so it's impossible for everyone to be connected
Constraints
- 2 ≤ n ≤ 100
- 1 ≤ logs.length ≤ 104
- logs[i].length == 3
- 0 ≤ logs[i][1], logs[i][2] ≤ n - 1
- logs[i][0] ≤ 109
- logs[i][1] ≠ logs[i][2]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Friendship logs with timestamps and people pairs
2
Process
Sort by time and track connected components
3
Output
Timestamp when everyone is in one group
Key Takeaway
🎯 Key Insight: Use Union-Find to efficiently track when separate friend groups merge into one big connected community
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code