The transitive part is what makes this click as a Union-Find problem.
Sort the friendship events by timestamp and process them in chronological order using a Union-Find (Disjoint Set Union) data structure. After each union, check if the number of connected components has reduced to 1; if so, return the current timestamp. If all events are processed without full connectivity, return -1.
Pro tip: Mention that you can optimize by tracking the number of components and early-exiting when it reaches 1, and discuss the trade-offs between sorting upfront versus using a min-heap for streaming data.
Confirm that the graph is undirected, timestamps may be unsorted, and multiple events can occur at the same timestamp. Discuss edge cases like n=1 (already connected) or no events.
Select Union-Find with path compression and union by rank for near-constant time operations. Alternatively, consider BFS/DFS after sorting, but explain why Union-Find is more efficient for incremental connectivity.
Sort the events by timestamp. Initialize Union-Find with n components. For each event, union the two people and decrement the component count if they were in different sets.
After each union, if the component count becomes 1, return the current timestamp immediately. If the loop finishes without reaching 1, return -1.
State time complexity: O(m log m) for sorting plus O(m α(n)) for unions, where m is number of events. Space: O(n). Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.