KatInterview

First Moment a Cable Network Becomes One Piece

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsunion-findgraph-connectivitysorting

Last updated

Replay unsorted timed link events and find the earliest timestamp at which every node is in one connected group, using union-find over events sorted by time.

Network Fully Linked

A network has n machines numbered 0 through n - 1. At the start, no machine is linked to any other.

You receive a list links. Each entry is [time, a, b] and means that at moment time, a two-way link appeared between machine a and machine b. Links never disappear once created.

Two machines are in the same group if you can travel from one to the other by following links that have already appeared. The network is fully linked at a given moment when all n machines are in a single group.

Return the smallest time value such that, using only the links whose time is less than or equal to that value, the network is fully linked. If that never happens, return -1.

Notes

  • The list links is not sorted by time.
  • Several links may share the same time, and the same pair of machines may be linked more than once (at equal or different times). A link between machines already in the same group changes nothing.
  • A time of 0 is a legitimate answer.
  • The returned value is always one of the time values from the input, or -1.

Constraints

  • 2 <= n <= 10^5
  • 1 <= len(links) <= 2 * 10^5
  • Each entry is [time, a, b] with 0 <= time <= 10^9
  • 0 <= a, b < n and a != b

Examples

Example 1

Input: earliest_full_link_time(4, [[20230101, 0, 1], [20230104, 2, 3], [20230102, 1, 2], [20230103, 0, 2]])

Output: 20230104

Example 2

Input: earliest_full_link_time(4, [[5, 0, 1], [10, 1, 2]])

Output: -1

Hints

Hint 1

Once two machines are connected they stay connected, so think about processing the links from earliest to latest and tracking how many groups remain.

Hint 2

A union-find (disjoint set) structure lets you check whether two machines are already in the same group and merge groups in nearly constant time.

Hint 3

Sort by time first. Each successful merge reduces the group count by one; the answer is the time of the merge that brings the count to 1. If that never happens, return -1.