In The Earliest Moment When Everyone Become Friends coding problem, you are given a list of logs, where each log contains a timestamp and the IDs of two people who became friends. Friendship is mutual and transitive (if A is friends with B and B is friends with C, then A is friends with C). Your task is to find the earliest timestamp at which everyone in the group is connected to each other as friends. If this never happens, return -1.
Google and Expedia ask this "Medium" level question to test a candidate's knowledge of the Union Find data structure. It evaluates whether you can handle chronological events and maintain group connectivity efficiently. It's a classic application of the "Disjoint Set Union" (DSU) pattern, requiring you to track the number of connected components in a graph as edges are added over time.
The primary algorithmic pattern is Union Find and Sorting.
n people. Keep track of the number of connected components (initially n).(timestamp, personA, personB):
union operation on personA and personB.Logs: [(2, 0, 1), (5, 2, 3), (1, 1, 2)], n = 4.
[(1, 1, 2), (2, 0, 1), (5, 2, 3)].{0}, {1, 2}, {3}. Count = 3.{0, 1, 2}, {3}. Count = 2.{0, 1, 2, 3}. Count = 1.
Result: Timestamp 5.A common mistake is not sorting the logs by timestamp first, which leads to incorrect results if friendship events are processed out of order. Another error is not efficiently implementing the Union Find structure (e.g., failing to use path compression or union by rank/size), which can lead to O(n) operations instead of nearly O(1). Some also forget to initialize the component count correctly.
When preparing for The Earliest Moment When Everyone Become Friends coding problem, master the Union Find interview pattern. It is the go-to solution for any problem involving "connectivity" or "group merging." Being able to explain the "transitive property" of friendship in terms of graph components will impress your interviewer.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Make Lexicographically Smallest Array by Swapping Elements | Medium | Solve | |
| Check if Grid can be Cut into Sections | Medium | Solve | |
| Count Days Without Meetings | Medium | Solve | |
| Sort the Jumbled Numbers | Medium | Solve | |
| Merge Intervals | Medium | Solve |