Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array of unique positive integers nums. Consider the following graph:
nums.length nodes, labeled nums[0] to nums[nums.length - 1],nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.Return the size of the largest connected component in the graph.
Example 1:
Input: nums = [4,6,15,35] Output: 4
Example 2:
Input: nums = [20,50,9,63] Output: 2
Example 3:
Input: nums = [2,3,6,7,4,12,21,39] Output: 8
Constraints:
1 <= nums.length <= 2 * 1041 <= nums[i] <= 105nums are unique.Problem summary: You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math · Union-Find
[4,6,15,35]
[20,50,9,63]
[2,3,6,7,4,12,21,39]
groups-of-strings)distinct-prime-factors-of-product-of-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #952: Largest Component Size by Common Factor
class UnionFind {
int[] p;
UnionFind(int n) {
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
}
void union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa != pb) {
p[pa] = pb;
}
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
class Solution {
public int largestComponentSize(int[] nums) {
int m = 0;
for (int v : nums) {
m = Math.max(m, v);
}
UnionFind uf = new UnionFind(m + 1);
for (int v : nums) {
int i = 2;
while (i <= v / i) {
if (v % i == 0) {
uf.union(v, i);
uf.union(v, v / i);
}
++i;
}
}
int[] cnt = new int[m + 1];
int ans = 0;
for (int v : nums) {
int t = uf.find(v);
++cnt[t];
ans = Math.max(ans, cnt[t]);
}
return ans;
}
}
// Accepted solution for LeetCode #952: Largest Component Size by Common Factor
func largestComponentSize(nums []int) int {
m := slices.Max(nums)
p := make([]int, m+1)
for i := range p {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
union := func(a, b int) {
pa, pb := find(a), find(b)
if pa != pb {
p[pa] = pb
}
}
for _, v := range nums {
i := 2
for i <= v/i {
if v%i == 0 {
union(v, i)
union(v, v/i)
}
i++
}
}
cnt := make([]int, m+1)
for _, v := range nums {
t := find(v)
cnt[t]++
}
return slices.Max(cnt)
}
# Accepted solution for LeetCode #952: Largest Component Size by Common Factor
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa != pb:
self.p[pa] = pb
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
class Solution:
def largestComponentSize(self, nums: List[int]) -> int:
uf = UnionFind(max(nums) + 1)
for v in nums:
i = 2
while i <= v // i:
if v % i == 0:
uf.union(v, i)
uf.union(v, v // i)
i += 1
return max(Counter(uf.find(v) for v in nums).values())
// Accepted solution for LeetCode #952: Largest Component Size by Common Factor
/**
* [0952] Largest Component Size by Common Factor
*
* You are given an integer array of unique positive integers nums. Consider the following graph:
*
* There are nums.length nodes, labeled nums[0] to nums[nums.length - 1],
* There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.
*
* Return the size of the largest connected component in the graph.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2018/12/01/ex1.png" style="width: 500px; height: 97px;" />
* Input: nums = [4,6,15,35]
* Output: 4
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2018/12/01/ex2.png" style="width: 500px; height: 85px;" />
* Input: nums = [20,50,9,63]
* Output: 2
*
* Example 3:
* <img alt="" src="https://assets.leetcode.com/uploads/2018/12/01/ex3.png" style="width: 500px; height: 260px;" />
* Input: nums = [2,3,6,7,4,12,21,39]
* Output: 8
*
*
* Constraints:
*
* 1 <= nums.length <= 2 * 10^4
* 1 <= nums[i] <= 10^5
* All the values of nums are unique.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/largest-component-size-by-common-factor/
// discuss: https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Credit: https://leetcode.com/problems/largest-component-size-by-common-factor/solutions/1592428/rust-unionfind-solution/
struct UnionFind {
parent: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> Self {
Self {
parent: (0..n).collect(),
}
}
fn union(&mut self, x: usize, y: usize) {
let x = self.find(x);
let y = self.find(y);
self.parent[y] = x
}
fn find(&mut self, x: usize) -> usize {
if x != self.parent[x] {
self.parent[x] = self.find(self.parent[x]);
}
self.parent[x]
}
}
impl Solution {
pub fn largest_component_size(nums: Vec<i32>) -> i32 {
let mut sieve = (0..100_001).collect::<Vec<_>>();
for i in (2..).take_while(|&i| i * i < 100_001) {
if sieve[i] == i as i32 {
for j in (i..100_001).step_by(i) {
sieve[j] = sieve[j].min(i as i32);
}
}
}
let mut hm = std::collections::HashMap::new();
for (i, &num) in nums.iter().enumerate() {
let mut n = num;
while n > 1 {
let p = sieve[n as usize];
hm.entry(p).or_insert_with(Vec::new).push(i);
n /= p as i32;
}
}
let mut uf = UnionFind::new(nums.len());
for v in hm.values_mut() {
v.dedup();
v.windows(2).for_each(|w| uf.union(w[0], w[1]));
}
let mut counts = vec![0; nums.len()];
for i in 0..nums.len() {
counts[uf.find(i)] += 1;
}
*counts.iter().max().unwrap() as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0952_example_1() {
let nums = vec![4, 6, 15, 35];
let result = 4;
assert_eq!(Solution::largest_component_size(nums), result);
}
#[test]
fn test_0952_example_2() {
let nums = vec![20, 50, 9, 63];
let result = 2;
assert_eq!(Solution::largest_component_size(nums), result);
}
#[test]
fn test_0952_example_3() {
let nums = vec![2, 3, 6, 7, 4, 12, 21, 39];
let result = 8;
assert_eq!(Solution::largest_component_size(nums), result);
}
}
// Accepted solution for LeetCode #952: Largest Component Size by Common Factor
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #952: Largest Component Size by Common Factor
// class UnionFind {
// int[] p;
//
// UnionFind(int n) {
// p = new int[n];
// for (int i = 0; i < n; ++i) {
// p[i] = i;
// }
// }
//
// void union(int a, int b) {
// int pa = find(a), pb = find(b);
// if (pa != pb) {
// p[pa] = pb;
// }
// }
//
// int find(int x) {
// if (p[x] != x) {
// p[x] = find(p[x]);
// }
// return p[x];
// }
// }
//
// class Solution {
// public int largestComponentSize(int[] nums) {
// int m = 0;
// for (int v : nums) {
// m = Math.max(m, v);
// }
// UnionFind uf = new UnionFind(m + 1);
// for (int v : nums) {
// int i = 2;
// while (i <= v / i) {
// if (v % i == 0) {
// uf.union(v, i);
// uf.union(v, v / i);
// }
// ++i;
// }
// }
// int[] cnt = new int[m + 1];
// int ans = 0;
// for (int v : nums) {
// int t = uf.find(v);
// ++cnt[t];
// ans = Math.max(ans, cnt[t]);
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.