Earliest Moment a Social Network Becomes Fully Connected
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests offline dynamic graph connectivity using a segment-tree-over-time with a rollback-capable union-find to handle both edge insertions and deletions.
Problem
You are given a chronological log of interactions between people in a social network. Each entry is a list of four values:
[timestamp, person_A, event_type, person_B]
There are two event types:
"shared-ride-with"—person_Aandperson_Bformed a direct connection at the given timestamp."blocked"— starting at the given timestamp, the direct connection betweenperson_Aandperson_Bis severed (even if they connected earlier).
Two people are reachable from each other if a chain of active direct connections links them. Reachability is transitive: if A is connected to B and B is connected to C, then A can reach C.
Your task is to find the earliest timestamp at which every person who appears anywhere in the log belongs to a single connected group. If this never happens, return -1.
Rules and Edge Cases
- Timestamps are given as integers (already parsed; no string conversion needed).
- Events that share the same timestamp are applied in the order they appear in the input list. Connectivity is checked after each individual event.
- A
"shared-ride-with"event between two people who are already directly connected does not reset or duplicate their connection interval. - A
"blocked"event between two people who are not currently directly connected is a no-op. - A person can reconnect with someone they previously blocked; the new connection starts a fresh interval from that event onward.
- A
"shared-ride-with"event where both names are the same adds no connection. A log containing only one distinct person is considered fully connected from the first event's timestamp. - Every person who appears in any event — including those who appear only in
"blocked"events — counts toward the group that must become fully connected. - If the log is empty, return
-1. - If any event does not have exactly four fields, or contains an unrecognized event type, raise a
ValueError. - Connections can come and go. If the network was fully connected at some earlier moment but later split due to a block, the answer is still that earlier timestamp.
Constraints
0 ≤ len(events) ≤ 10^4- Each event has the form
[timestamp, name_A, event_type, name_B] - Timestamps are non-negative integers
- Names are non-empty strings
event_typeis either"shared-ride-with"or"blocked"; any other value raisesValueError- An event with fewer or more than 4 fields raises
ValueError
Examples
Example 1
Input: earliest_all_connected_time([[1, 'Alice', 'shared-ride-with', 'Bob'], [2, 'Charlie', 'shared-ride-with', 'Dan'], [3, 'Bob', 'shared-ride-with', 'Charlie'], [4, 'Alice', 'shared-ride-with', 'Eve'], [5, 'Bob', 'shared-ride-with', 'Dan']])
Output: 4
Example 2
Input: earliest_all_connected_time([[1, 'A', 'shared-ride-with', 'B'], [2, 'C', 'shared-ride-with', 'D']])
Output: -1
Hints
Hint 1
For the add-only version (no blocks), a plain union-find processed in time order is enough — each merge reduces the component count by one, and you stop the moment it hits 1.
Hint 2
Once block events are introduced, edges have lifetimes: an edge is active over a contiguous interval of sorted-event slots, from when it is created to when it is blocked. Try representing each edge as one or more half-open slot intervals [start, end).
Hint 3
Build a segment tree whose leaves correspond to sorted event slots and insert each interval into O(log n) canonical nodes. Then DFS the tree left-to-right with a union-find that supports undo (union-by-size, no path compression), rolling back on exit from each node. The first leaf where the component count reaches 1 gives the answer.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Add-only case (no blocks)
When connections only accumulate, reachability can never shrink. A plain union-find is all you need: sort events by time, process them one by one, and union the two people involved in each "shared-ride-with" event. Every successful merge reduces the number of connected components by one. The moment the component count hits 1, you have your answer.
The two-event sample shows this: after C shared-ride-with D, there are still two separate groups, so the answer is -1.
Full solution: edges have lifetimes
"blocked" events remove edges, so reachability is no longer monotone. A standard union-find cannot delete edges. The key insight is to work offline — the entire log is available upfront — and reframe the problem:
Every edge is active over one or more contiguous half-open intervals of sorted-event slots
[start, end). The question becomes: at which leaf slot does the set of simultaneously active edges make every person reachable from every other?
Step 1 — Sort and assign slots. Sort events by (timestamp, original index) to honour input order within a tie. Each position i in the sorted list is one slot. Record times[i] for the final answer lookup.
Step 2 — Extract edge intervals. Scan left to right:
"shared-ride-with"on an inactive edge opens an interval ati(stored inedge_start).- A repeated share while the edge is already active is ignored (the interval started earlier).
"blocked"on an active edge closes the interval ati, emitting(start, i, edge)."blocked"on an inactive edge is a no-op.- After scanning, every edge still open gets
end = n.
Step 3 — Segment tree over slots. Build a segment tree covering [0, n). For each interval [ql, qr) insert the edge into the O(log n) canonical tree nodes that tile the interval exactly. Each node therefore holds exactly the edges that are active throughout its entire slot range.
Step 4 — DFS with rollback union-find. Traverse the segment tree with a DFS. On entering a node, union every edge it stores and track how many components were merged. At a leaf, if the component count is 1, record times[leaf] as the answer. On leaving a node, undo every union performed on entry (union-by-size, no path compression — so undo costs O(1) per union via a history stack). The DFS visits leaves left to right, so the first leaf with one component is the earliest slot.
Why it is correct. The edges unioned along the root-to-leaf path for slot i are exactly those whose intervals contain i — no edge is missing and none is counted twice. Rollback means sibling subtrees never see each other's state changes, so each leaf sees a clean snapshot of its own active edges.
Why union-by-size without path compression? Path compression makes multiple pointer changes per find, breaking cheap rollback. Union-by-size bounds tree depth at O(log R) so find is still O(log R), giving efficient unions that are also trivially undoable with a single pointer restore.
Edge cases
- Empty log →
-1. - A person appearing only in
"blocked"events still counts toward the group. - Self-connections (
X shared-ride-with X) are skipped. - Duplicate shares of an active edge do not reset its interval.
- If the network achieves full connectivity and is later split by a block, the first time of full connectivity is still the answer.
- Events with wrong field counts or unknown types raise
ValueError.
Complexity
- Time:
O(n log n · log R)— sortingO(n log n), placingnintervals intoO(log n)nodes each, and each union/find costingO(log R)whereRis the number of people. - Space:
O(n log n)for edge lists across all tree nodes,O(R)for the DSU,O(log n)recursion depth.
from typing import List
def earliest_all_connected_time(events: List[List[str]]) -> int:
if not events:
return -1
# Validate all events and collect every person's name.
person_set = {}
for event in events:
if len(event) != 4:
raise ValueError(
"Each event must contain timestamp, person, event type, and other person"
)
_, a, etype, b = event
if etype not in ("shared-ride-with", "blocked"):
raise ValueError("Unsupported event type")
for name in (a, b):
if name not in person_set:
person_set[name] = name
# Sort events by (timestamp, original position) to break ties in input order.
ordered = sorted(enumerate(events), key=lambda item: (int(item[1][0]), item[0]))
times = [int(ev[0]) for _, ev in ordered]
n = len(events)
# Build half-open slot intervals [start, end) for every edge lifetime.
edge_start: dict = {}
intervals: list = []
for i, (_, event) in enumerate(ordered):
_, a, etype, b = event
edge = tuple(sorted((a, b)))
if a == b:
continue # self-connection, skip
if etype == "shared-ride-with":
if edge not in edge_start:
edge_start[edge] = i
else: # "blocked"
if edge in edge_start:
start = edge_start.pop(edge)
if start < i:
intervals.append((start, i, edge))
# Edges still open at the end of the log are active through slot n.
for edge, start in edge_start.items():
intervals.append((start, n, edge))
# Segment tree over slot indices [0, n).
tree = [[] for _ in range(4 * n)]
def add_interval(node: int, left: int, right: int, ql: int, qr: int, edge):
if ql <= left and right <= qr:
tree[node].append(edge)
return
mid = (left + right) // 2
if ql < mid:
add_interval(node * 2, left, mid, ql, qr, edge)
if qr > mid:
add_interval(node * 2 + 1, mid, right, ql, qr, edge)
for start, end, edge in intervals:
if start < end:
add_interval(1, 0, n, start, end, edge)
# Rollback-capable union-find (union-by-size, no path compression).
rb_parent = dict(person_set)
rb_size = {name: 1 for name in person_set}
history: list = []
def find(x: str) -> str:
while rb_parent[x] != x:
x = rb_parent[x]
return x
def unite(a: str, b: str) -> bool:
ra, rb = find(a), find(b)
if ra == rb:
history.append(None)
return False
if rb_size[ra] < rb_size[rb]:
ra, rb = rb, ra
history.append((rb, ra, rb_size[ra]))
rb_parent[rb] = ra
rb_size[ra] += rb_size[rb]
return True
def undo(snapshot: int) -> None:
while len(history) > snapshot:
change = history.pop()
if change is not None:
child, root, old_size = change
rb_parent[child] = child
rb_size[root] = old_size
total_people = len(person_set)
answer = -1
def visit(node: int, left: int, right: int, components: int) -> None:
nonlocal answer
snapshot = len(history)
current = components
for a, b in tree[node]:
if unite(a, b):
current -= 1
if right - left == 1:
if current == 1:
answer = times[left]
else:
mid = (left + right) // 2
visit(node * 2, left, mid, current)
if answer == -1:
visit(node * 2 + 1, mid, right, current)
undo(snapshot)
visit(1, 0, n, total_people)
return answer