Largest Label Spread Across Graph Clusters
Trees & GraphsAuto-graded · 18 test casesLast 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^50 <= len(edges) <= 10^5- Each edge is given as
[u, v]where0 <= u, v <= n-1 - Node labels are the integers
0throughn-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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Breaking the problem into two steps
The spread of a cluster depends only on its smallest and largest labels — the internal wiring of edges does not matter. So the problem reduces to:
- Partition all nodes into clusters (connected components).
- Aggregate the min and max label per cluster, then return the largest difference.
Why Union-Find
Both DFS/BFS and Union-Find correctly solve step 1. Union-Find has two practical advantages here:
- It works directly on the edge list, so no adjacency list needs to be built.
- Its
findoperation is iterative, which sidesteps Python's default recursion limit (~1000 frames). A naive recursive DFS on a 100,000-node path graph would crash.
Algorithm walkthrough
Setup. Create parent[i] = i and size[i] = 1 for every node. Also create minimum[i] = i and maximum[i] = i.
Union phase. For each edge (u, v), call union(u, v):
- Find the root of each endpoint.
- If they share a root, they are already in the same cluster — do nothing.
- Otherwise, attach the smaller tree under the larger one (union by size). This keeps trees shallow.
find uses path halving: parent[x] = parent[parent[x]] before advancing. Every call flattens the tree a little, so future calls are faster.
Aggregation phase. Walk every node from 0 to n-1. For each node, find its root. If the node's label is smaller than minimum[root], update it; if larger than maximum[root], update that too. Since labels equal node indices here, this simply folds each integer into its cluster's running extremes.
Answer phase. Walk every node again. A node is a root when parent[node] == node. For each root, compute maximum[root] - minimum[root] and keep the largest value seen. Starting the answer at 0 handles the case where all clusters are singletons.
Why this is correct
- Two nodes share a root after all unions if and only if there is a path between them. Union-Find maintains exactly the transitive closure of the edge relation.
- Every node is visited in the aggregation phase, so no label is missed.
- Roots are counted exactly once, and every cluster has exactly one root.
- Isolated nodes become their own roots with min = max = their label, contributing a spread of
0. - Self-loops and duplicate edges cause
findto return the same root for both endpoints, makinguniona no-op — both are handled safely.
Complexity
Let V = n and E = len(edges).
- Time: O((V + E) · α(V)). With union by size and path halving, each union/find costs amortized inverse-Ackermann time, which is effectively constant in practice.
- Space: O(V) for
parent,size,minimum, andmaximum. No adjacency list is stored.
A DFS/BFS solution would be O(V + E) time but O(V + E) space because it needs the adjacency list.
Reference solution
from typing import List
def largest_cluster_spread(n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return
if size[ra] < size[rb]: # union by size
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
for u, v in edges:
union(u, v)
minimum = list(range(n))
maximum = list(range(n))
for node in range(n):
root = find(node)
if node < minimum[root]:
minimum[root] = node
if node > maximum[root]:
maximum[root] = node
answer = 0
for node in range(n):
if parent[node] == node: # only process roots
answer = max(answer, maximum[node] - minimum[node])
return answer