Skip to content
BytePatterns

Earliest Moment All Connected

MediumUnion-Find#union-find#sort-by-time~25m

Problem

A network has n machines numbered 0 to n minus 1. A log lists cable installations as [time, a, b], meaning machines a and b were linked at that time, and the log is not in time order. Messages travel over any chain of cables. Return the earliest time at which every machine can reach every other machine, or -1 if that never happens.

Examples

Input:  n = 5, logs = [[20, 0, 1], [3, 3, 4], [5, 1, 2], [9, 2, 3], [12, 0, 3]]
Output: 12
Why:    by time 9 the groups are {0} and {1, 2, 3, 4}; the cable at 12 joins them
Input:  n = 4, logs = [[0, 2, 0], [1, 0, 1], [3, 0, 3], [4, 1, 2], [7, 3, 1]]
Output: 3
Input:  n = 3, logs = [[1, 0, 1]]
Output: -1
Why:    edge case, machine 2 is never linked to anything

Hints

0 / 3

Stuck on the idea rather than the code? Disjoint Sets Basics covers it.