Count Connected Components in LCM Graph Problem
Description
LeetCode Problem 3378.
You are given an array of integers nums of size n and a positive integer threshold.
There is a graph consisting of n nodes with the i^th node having a value of nums[i]. Two nodes i and j in the graph are connected via an undirected edge if lcm(nums[i], nums[j]) <= threshold.
Return the number of connected components in this graph.
A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.
The term lcm(a, b) denotes the least common multiple of a and b.
Example 1:
Input: nums = [2,4,8,3,9], threshold = 5
Output: 4
Explanation:

The four connected components are (2, 4), (3), (8), (9).
Example 2:
Input: nums = [2,4,8,3,9,12], threshold = 10
Output: 2
Explanation:

The two connected components are (2, 3, 4, 8, 9), and (12).
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9- All elements of
numsare unique. 1 <= threshold <= 2 * 10^5
Solution
Approach: Union-Find over Multiples
If lcm(a, b) <= threshold, then that lcm is a common multiple of a and b that is at most threshold. So a and b are both joined to a shared value v <= threshold. This lets us avoid comparing pairs.
Use a union-find over the values 0..threshold. For every num in nums with num <= threshold, union num with each of its multiples up to threshold. Two numbers are in the same component exactly when they end up in the same set. Numbers larger than threshold cannot connect to anything (their lcm with any number exceeds threshold), so each is its own component.
The answer is the number of distinct roots among the small numbers plus the number of large numbers.
Complexity: time about O(threshold * log threshold * alpha) because each num visits threshold / num multiples (a harmonic sum); space O(threshold).
class DSU:
def __init__(self, n):
self.parent = {i: i for i in range(n)}
self.rank = {i: 0 for i in range(n)}
def make_set(self, v):
self.parent[v] = v
self.rank[v] = 1
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union_set(self, u, v):
u = self.find(u)
v = self.find(v)
if u != v:
if self.rank[u] < self.rank[v]:
u, v = v, u
self.parent[v] = u
if self.rank[u] == self.rank[v]:
self.rank[u] += 1
class Solution:
def countComponents(self, nums, threshold):
dsu = DSU(threshold + 1)
for num in nums:
for j in range(num, threshold + 1, num):
dsu.union_set(num, j)
unique_parents = set()
for num in nums:
if num > threshold:
unique_parents.add(num)
else:
unique_parents.add(dsu.find(num))
return len(unique_parents)