Timestamp When All Users Form a Single Connected Group
Trees & GraphsModel answerLast updated
Given users and a chronological log of pairwise interactions, determine when everyone first becomes transitively connected through interaction chains.
You're analyzing connection patterns in a social platform. You have:
- A collection of user identifiers
- A time-ordered sequence of interaction records, where each record shows two users interacting at a specific moment
Users become part of the same network if they've interacted directly, or if there's a path of interactions linking them. For instance, if Alice interacts with Bob, and Bob interacts with Carol, then Alice, Bob, and Carol all belong to the same network.
Determine the earliest moment when every user in your collection becomes part of a single unified network.
If they never all connect, return -1.
Input Format:
users: list of user identifiers (strings)logs: list of log entries, each formatted as"<timestamp> <user1> <user2> <event_type>"- Only events with type
"shared_ride"create connections
Example:
users = ["A", "B", "C", "D"]
logs = [
"100 A B shared_ride",
"120 C D shared_ride",
"150 B C shared_ride"
]
Output: 150
At time 100, A and B form one network. At time 120, C and D form a separate network. At time 150, when B and C interact, the two networks merge into one, connecting all four users for the first time.
Constraints:
- Timestamps are non-negative integers
- The log may contain users not in your target collection (they can act as bridges)
- User identifiers are case-sensitive strings
- Events are listed in chronological order
Hints
Hint 1
Think about how to efficiently track separate groups that merge over time as connections form
Hint 2
You need to detect the moment when the number of separate groups drops to exactly one, covering all target users
Hint 3
A disjoint-set structure lets you merge groups and query connectivity in nearly constant time
Hint 4
Track how many of your target users belong to each group's root to know when you've connected everyone
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to track dynamic connectivity in a graph where edges appear over time. The optimal data structure is Union-Find (Disjoint Set Union), which efficiently handles:
- Grouping elements into components
- Merging components
- Checking if elements share a component
Core Strategy
- Parse the log and extract events that create connections (type
"shared_ride") - Process events chronologically, using Union-Find to merge connected components
- Track progress toward full connectivity by counting how many target users each component contains
- Return immediately when a merge creates a component containing all target users
Key Insight: Counting Target Users per Component
Instead of checking all users after each merge, we maintain a counter at each component root showing how many target users it contains. When a merge produces a root with count equal to len(users), we've achieved full connectivity.
This works even when the log mentions additional people not in our target list—they can serve as bridges between target users without needing to be connected themselves.
Algorithm Details
Union-Find with Enhancements:
- Path compression (or path halving): flatten trees during find operations
- Union by size: attach smaller tree to larger tree to keep depth low
- Target counting: each root tracks how many target users its component contains
Processing:
For each event in chronological order:
Add both users to Union-Find if not already present
Find roots of both users
If roots differ:
Merge the components (union by size)
Sum the target counts from both roots
If the new root's target count equals total target users:
Return this event's timestamp
Return -1 if we finish without connecting everyone
Complexity Analysis
- Time: O(E log E + E · α(N))
- E log E for sorting events if needed (O(E) if already sorted via Timsort)
- E · α(N) for E union operations, where α is the inverse Ackermann function (effectively constant)
- N is the total number of distinct users (targets plus bridges)
- Space: O(N) for Union-Find structures, O(E) for storing events if sorting is required
Edge Cases
- Empty or single user: Return
0(trivially connected)—confirm this convention - Users never appearing in logs: Impossible to connect, return
-1 - Self-interactions or duplicate pairs: Union-Find handles these as no-ops
- Bridge users: Non-target users in logs can connect target users transitively
- Multiple events at same timestamp: Order doesn't matter, any will give correct result
- Malformed log lines: Skip and continue processing
Implementation
from typing import List, Set
def find_connectivity_time(users: List[str], logs: List[str]) -> int:
targets = set(users)
total_targets = len(targets)
if total_targets <= 1:
return 0
# Parse relevant events
events = []
for line in logs:
parts = line.split()
if len(parts) < 4 or parts[3] != "shared_ride":
continue
try:
timestamp = int(parts[0])
events.append((timestamp, parts[1], parts[2]))
except ValueError:
continue
# Sort if needed (already sorted in this problem)
events.sort()
# Union-Find structures
parent = {}
size = {}
target_count = {}
def initialize(user: str):
if user not in parent:
parent[user] = user
size[user] = 1
target_count[user] = 1 if user in targets else 0
def find(user: str) -> str:
# Path halving
while parent[user] != user:
parent[user] = parent[parent[user]]
user = parent[user]
return user
def union(u1: str, u2: str) -> int:
root1, root2 = find(u1), find(u2)
if root1 == root2:
return target_count[root1]
# Union by size
if size[root1] < size[root2]:
root1, root2 = root2, root1
parent[root2] = root1
size[root1] += size[root2]
target_count[root1] += target_count[root2]
return target_count[root1]
# Process events
for timestamp, user1, user2 in events:
initialize(user1)
initialize(user2)
count = union(user1, user2)
if count == total_targets:
return timestamp
return -1
Common Mistakes
- Not handling bridge users: The solution must allow non-target users in the log to connect targets
- Checking connectivity after every event: Too slow; maintain counts instead
- Forgetting to sort: If the log isn't guaranteed sorted, you must sort first
- Early termination errors: Must process all events with the same timestamp as the answer
- Duplicate users in input: Use a set to deduplicate the target user list
Extension: Unsorted or Streaming Logs
If events can arrive out of order:
- Small disorder: Buffer recent events and process up to a watermark
- Fully streaming, sorted: Process line-by-line, no need to store all events
- Fully unsorted: Must collect all events, sort, then process—cannot give final answer until stream ends
Time complexity remains the same, but streaming reduces space to O(N) when events are processed incrementally.