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
The Earliest Moment When Everyone Become FriendsInput: logs = [[20,0,1],[5,2,3],[15,3,4],[18,0,2]], n = 5Time 52-3 friends4 componentsTime 153-4 friends3 componentsTime 180-2 friends2 componentsTime 200-1 friends1 component!Union-Find tracks components efficiently: O(mα(n)) timeSort events → Process chronologically → Find first moment all connectedOutput: 20 (everyone connected at time 20)
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
Asked in
Facebook 25 Google 15
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen