KatInterview

Timestamp When All Users Form a Single Connected Group

Trees & GraphsModel answer
MediumModel answerTrees & Graphsunion-findgraph-connectivitytemporal-graph

Last 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