15% off all plans & roadmaps Use code
See plansLeetCode 1101 · Solution & editorial
You are given an integer n representing the number of people in a social group, labeled from 0 to n - 1. You are also given a list of logs logs, where each logs[i] = [timestamp, x, y] indicates that person x and person y became friends at time timestamp.
The Earliest Moment When Everyone Become Friends is a Graph Traversal Patterns (DFS & BFS) problem, in the Union-Find (Disjoint Set Union - DSU) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Master Union-Find data structure with path compression and union by rank for connectivity problems.
The reference solution runs in O(nlogn) time and O(n) space.
The Earliest Moment When Everyone Become Friends has been reported in interviews at Google.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
The Earliest Moment When Everyone Become Friends is a Graph Traversal Patterns (DFS & BFS) problem, in the Union-Find (Disjoint Set Union - DSU) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.