KatInterview

Network Unification Timestamp

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsunion-finddisjoint-setgraph-connectivity

Last updated

Tests Union-Find data structure application to track dynamic graph connectivity and determine when all nodes merge into one component.

You have n nodes numbered from 0 to n-1. At the beginning, every node is isolated. You receive a list of connections edges, where each entry edges[i] = [u, v, t] means nodes u and v get linked at timestamp t.

Every timestamp in the input is distinct. The graph becomes "unified" when you can reach any node from any other node through the available connections. Return the smallest timestamp at which unification occurs. If the nodes never form a single connected component, return -1.

Constraints

  • 2 <= n <= 10^5
  • 1 <= len(edges) <= 10^5
  • 0 <= u, v < n
  • u and v may be equal (self-loop)
  • All timestamp values t are unique positive integers
  • The same pair of nodes may appear in multiple edges with different timestamps

Examples

Example 1

Input: network_unification_time(4, [[0, 1, 10], [1, 2, 15], [2, 3, 20]])

Output: 20

Example 2

Input: network_unification_time(3, [[0, 1, 5], [0, 2, 10]])

Output: 10

Hints

Hint 1

Consider processing connections in chronological order and tracking how many separate components remain after each connection is added.

Hint 2

Union-Find (Disjoint Set Union) provides efficient operations to merge components and check if two nodes belong to the same component.

Hint 3

The graph is unified when the number of distinct components drops to exactly one.