Problem Description
Given an array of unique positive integers, treat each number as a node in a graph. Two nodes share an undirected edge if the corresponding numbers share a common factor greater than 1. The task is to determine the size of the largest connected component in this graph.
Key Insights
- Recognize that common factors (other than 1) can connect numbers.
- Instead of building an explicit graph, use factorization to connect numbers sharing any factor.
- Use the Union-Find (Disjoint Set Union) data structure to dynamically merge nodes that share common factors.
- For each number, factorize it and union together all numbers that have the same factor.
- The largest connected component size is equivalent to the largest set in the Union-Find data structure.
Space and Time Complexity
Time Complexity: O(n * sqrt(m) * α(n)) where n is the number of elements, m is the maximum value in nums (due to factorization up to sqrt(m)), and α(n) is the inverse Ackerman function from union-find operations which is almost constant. Space Complexity: O(n + m) for storing the union-find data structure and factor mapping.
Solution
The solution uses the Union-Find algorithm with path compression to connect nodes that share common factors greater than 1. For each number in the array, we perform the following:
- Factorize the number by checking divisibility up to its square root.
- For each factor found (and its complementary factor), use a mapping to union the current number with previously seen numbers that share the same factor.
- Finally, count the size of each component by iterating through the union-find parent references to find the largest connected component.
This approach avoids the overhead of constructing an explicit graph by directly linking numbers based on shared factors.