#3378

Count Connected Components in LCM Graph

Hard
ArrayHash TableMathUnion-FindNumber TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Use Union-Find to efficiently group numbers by connecting multiples that are less than the threshold, reducing unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a Union-Find structure to manage connected components.
  2. 2Step 2: For each number, connect it to all its multiples that are less than or equal to the threshold.
  3. 3Step 3: Count the distinct roots in the Union-Find structure to determine the number of connected components.
solution.py20 lines
1class UnionFind:
2    def __init__(self, size):
3        self.parent = list(range(size))
4    def find(self, x):
5        if self.parent[x] != x:
6            self.parent[x] = self.find(self.parent[x])
7        return self.parent[x]
8    def union(self, x, y):
9        rootX = self.find(x)
10        rootY = self.find(y)
11        if rootX != rootY:
12            self.parent[rootY] = rootX
13
14def countComponents(nums, threshold):
15    uf = UnionFind(len(nums))
16    for i in range(len(nums)):
17        for j in range(2, threshold // nums[i] + 1):
18            if j * nums[i] in nums:
19                uf.union(i, nums.index(j * nums[i]))
20    return len(set(uf.find(i) for i in range(len(nums))))

Complexity note: The complexity is linearithmic due to the union-find operations and multiple connections.

  • 1Use Union-Find for efficient grouping.
  • 2LCM properties can reduce unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.