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: 1
💡 Note: LCM(2,6) = 6 ≤ 6, so nodes 0,1 connect. LCM(2,3) = 6 ≤ 6, so nodes 0,2 connect. LCM(2,4) = 4 ≤ 6, so nodes 0,3 connect. LCM(6,3) = 6 ≤ 6, so nodes 1,2 connect. This forms one component {0,1,2,3}. Total: 1 component.
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
Count Connected Components in LCM Graph INPUT nums = [2, 6, 3, 4] 2 i=0 6 i=1 3 i=2 4 i=3 threshold = 6 Initial Graph Nodes: 2 6 3 4 lcm(2,4)=4, lcm(2,6)=6, lcm(3,6)=6 lcm(2,3)=6, lcm(4,6)=12, lcm(3,4)=12 ALGORITHM STEPS 1 Initialize Union-Find parent[i] = i for all nodes 2 Check LCM pairs If lcm(a,b) <= 6, union them 3 Union Operations Connect valid pairs Union Operations: lcm(2,4)=4 <= 6 --> union(2,4) lcm(2,6)=6 <= 6 --> union(2,6) lcm(3,6)=6 <= 6 --> union(3,6) lcm(2,3)=6 <= 6 --> union(2,3) lcm(4,6)=12 > 6 --> skip lcm(3,4)=12 > 6 --> skip 4 Count Components Count unique roots FINAL RESULT Connected Components: Component 1 2 6 3 Component 2 4 Output: 2 Components Found OK - 2 connected components Key Insight: Union-Find efficiently tracks connected components. For each pair (i,j), compute lcm(nums[i], nums[j]). If lcm <= threshold, union the nodes. Finally, count distinct roots to get the number of components. Time complexity: O(n^2 * alpha(n)) where alpha is the inverse Ackermann function (nearly constant). TutorialsPoint - Count Connected Components in LCM Graph | Union-Find (Disjoint Set) Approach
Asked in
Google 12 Microsoft 8 Amazon 6
8.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen