The Earliest Moment When Everyone Become Friends - Problem
You're managing a social network where friendships form over time. Given n people labeled from 0 to n-1, you need to find the earliest moment when everyone becomes connected in one giant social circle.
You're given an array logs where logs[i] = [timestamp, x, y] indicates that person x and person y become friends at time timestamp. Remember:
- Friendship is symmetric: if A is friends with B, then B is friends with A
- Friendship is transitive through acquaintances: if A knows B and B knows C, then A is acquainted with C
Goal: Return the earliest timestamp when every person is acquainted with every other person (directly or through mutual friends). If this never happens, return -1.
Example: With 4 people and friendships forming at different times, you need to find when the last "island" of people connects to form one unified group.
Input & Output
example_1.py โ Basic Friendship Network
$
Input:
logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6
โบ
Output:
20190301
๐ก Note:
At timestamp 20190301, when persons 0 and 3 become friends, it connects the final two separate groups: {0,1,5,2} and {3,4}, making everyone acquainted.
example_2.py โ Already Connected Small Group
$
Input:
logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
โบ
Output:
3
๐ก Note:
After timestamp 3, all 4 people are connected: 0-2-1 and 0-3 form one connected component covering everyone.
example_3.py โ Impossible Connection
$
Input:
logs = [[9,3,0],[0,2,1],[8,0,1],[1,3,2],[2,2,0],[5,3,1]], n = 4
โบ
Output:
2
๐ก Note:
All people become connected at timestamp 2 when the friendship network forms a complete connected graph.
Constraints
- 1 โค n โค 100
- 1 โค logs.length โค 104
- logs[i].length == 3
- 0 โค timestampi โค 109
- 0 โค xi, yi โค n - 1
- xi โ yi
- All timestamps are distinct
- All friendships are bidirectional
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Everyone starts as isolated individuals (n separate components)
2
First Connections
Early friendships create small groups, reducing total components
3
Group Merging
Strategic friendships merge existing groups into larger networks
4
Final Connection
The last friendship connects all groups into one unified network
Key Takeaway
๐ฏ Key Insight: Union-Find transforms an O(nยฒm) connectivity problem into an elegant O(m log n) solution by tracking components instead of individual connections!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code