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 Friends INPUT n = 5 people 0 1 2 3 4 logs array: [20, 0, 1] [5, 2, 3] [15, 3, 4] [18, 0, 2] [timestamp, person_x, person_y] ALGORITHM STEPS 1 Sort by timestamp [5,2,3] [15,3,4] [18,0,2] [20,0,1] 2 Init Union-Find parent[i]=i, components=5 3 Process logs Union x and y for each log t=5: union(2,3) comp=4 t=15: union(3,4) comp=3 t=18: union(0,2) comp=2 t=20: union(0,1) comp=1 Groups merging: {0}{1}{2}{3}{4} ---> {0,1,2,3,4} All connected at t=20! 4 Check components Return time when comp==1 FINAL RESULT Everyone connected at t=20 0 1 2 3 4 Output: 20 OK - All 5 people connected Single component formed at timestamp 20 Key Insight: Union-Find efficiently tracks connected components. By sorting logs by timestamp and processing them in order, we can detect the exact moment when all people become part of a single group. Time: O(N log N + M * alpha(N)) where alpha is inverse Ackermann. Space: O(N) for parent array. TutorialsPoint - The Earliest Moment When Everyone Become Friends | Union-Find (Disjoint Set Union)
Asked in
Facebook 25 Google 15
32.1K 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