KatInterview

Largest Label Spread Across Graph Clusters

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsunion-findgraphsconnected-components

Last updated

Tests ability to find connected components in an undirected graph and compute the maximum difference between the highest and lowest node labels in any single component.

Problem

You have an undirected graph with n nodes. Each node carries an integer label from 0 to n-1. Two nodes belong to the same cluster if there is a path of edges connecting them. Isolated nodes (no edges) each form a cluster on their own.

Define the spread of a cluster as:

spread = (largest label in the cluster) - (smallest label in the cluster)

A cluster containing a single node has a spread of 0.

Given the number of nodes n and a list of undirected edges, return the largest spread among all clusters.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 10^5
  • Each edge is given as [u, v] where 0 <= u, v <= n-1
  • Node labels are the integers 0 through n-1 (each used exactly once)
  • Self-loops and duplicate edges are possible
  • The answer is never negative

Examples

Example 1

Input: largest_cluster_spread(4, [[0, 1], [2, 3]])

Output: 1

Example 2

Input: largest_cluster_spread(5, [[0, 1], [1, 2], [3, 4]])

Output: 2

Hints

Hint 1

Start by figuring out which nodes belong together — this is a classic connected-components problem. BFS, DFS, or Union-Find all work.

Hint 2

You only need two numbers per cluster to compute its spread: the minimum label and the maximum label. You do not need to store every member.

Hint 3

Union-Find with union-by-size and path compression is a clean fit here: process each edge with a union, then walk every node once to fold its label into its root's running min and max.