You are given a time-ordered log of events involving Uber riders. Each event has a timestamp and two rider names.
Event types:
-
t X shared-ride-with Y
— riders
X
and
Y
shared a ride at time
t
, which creates an (undirected) connection between them.
Two riders are considered connected if there is a path of shared rides between them (transitive connectivity). For example, if A shared with B and B shared with C, then A is connected to C.
Example (already sorted by time):
-
t1 Alice shared-ride-with Bob
-
t2 Charlie shared-ride-with Dan
-
t3 Bob shared-ride-with Charlie
-
t4 Alice shared-ride-with Eve
-
t5 Bob shared-ride-with Dan
Task:
-
Return the
earliest timestamp
at which
all riders that appear in the logs
become connected in a single connected component. If this never happens, return an appropriate value (e.g.,
-1
).
Follow-up:
The log may also contain block events:
-
t X blocked Y
— starting at time
t
, treat riders
X
and
Y
as
no longer directly connected by their shared-ride relationship
(i.e., the edge between
X
and
Y
is removed for times
>= t
, even if they shared earlier).
How would you modify your approach to still find the earliest time when all riders are connected, given that connections can be both added (shared-ride-with) and removed (blocked)?