Count Connected Components in LCM Graph - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,6,3,4], threshold = 6
›
Output:
2
💡 Note:
LCM(2,6) = 6 ≤ 6, so nodes 0,1 connect. LCM(6,3) = 6 ≤ 6, so nodes 1,2 connect. This forms one component {0,1,2}. Node 3 is isolated since LCM(4,x) > 6 for all other values. Total: 2 components.
Example 2 — All Disconnected
$
Input:
nums = [3,4,6,8], threshold = 2
›
Output:
4
💡 Note:
All LCM values exceed threshold 2: LCM(3,4)=12, LCM(3,6)=6, LCM(3,8)=24, etc. No connections exist, so each node forms its own component.
Example 3 — All Connected
$
Input:
nums = [1,2,3], threshold = 6
›
Output:
1
💡 Note:
LCM(1,2)=2≤6, LCM(1,3)=3≤6, LCM(2,3)=6≤6. All nodes are connected in one large component.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 105
- 1 ≤ threshold ≤ 1015
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of numbers and threshold value
2
Build Connections
Connect pairs where LCM ≤ threshold
3
Count Components
Find separate connected groups
Key Takeaway
🎯 Key Insight: Build a graph where edges connect numbers with LCM ≤ threshold, then count connected components using Union-Find or DFS
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code