Solving Leetcode Interviews in Seconds with AI: Count Connected Components in LCM Graph
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3378" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 ith 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. Example 1: Input: nums = [2,4,8,3,9], threshold = 5 Output: 4 Explanation: The four connected components are (2, 4), (3), (8), (9). Example 2: Input: nums = [2,4,8,3,9,12], threshold = 10 Output: 2 Explanation: The two connected components are (2, 3, 4, 8, 9), and (12). Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 All elements of nums are unique. 1 <= threshold <= 2 * 105
Explanation
Here's the approach to solve this problem efficiently:
- Disjoint Set Union (DSU): Use DSU to efficiently track connected components. Iterate through all possible pairs of nodes, and if their LCM is within the threshold, union them into the same component.
- LCM Calculation: Calculate the Least Common Multiple (LCM) efficiently using the formula: LCM(a, b) = (a * b) / GCD(a, b), where GCD is the Greatest Common Divisor.
Connected Component Count: After processing all pairs, iterate through the nodes, find the representative (root) of each node using the
findoperation of DSU, and count the distinct representatives to find the number of connected components.Runtime & Storage Complexity: O(n2 * log(max(nums))) time complexity, primarily due to iterating through all pairs and GCD calculation. O(n) storage complexity for the DSU data structures.
Code
import math
def gcd(a, b):
"""Calculates the Greatest Common Divisor (GCD) of two integers."""
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
"""Calculates the Least Common Multiple (LCM) of two integers."""
return (a * b) // gcd(a, b)
def connected_components(nums, threshold):
"""
Calculates the number of connected components in a graph where nodes are connected
if their LCM is less than or equal to the threshold.
"""
n = len(nums)
parent = list(range(n)) # Initialize DSU parent array
def find(i):
"""Finds the representative (root) of a node."""
if parent[i] == i:
return i
parent[i] = find(parent[i]) # Path compression
return parent[i]
def union(i, j):
"""Unions two nodes into the same component."""
root_i = find(i)
root_j = find(j)
if root_i != root_j:
parent[root_i] = root_j
# Iterate through all pairs of nodes and union them if their LCM <= threshold
for i in range(n):
for j in range(i + 1, n):
if lcm(nums[i], nums[j]) <= threshold:
union(i, j)
# Count the number of connected components
num_components = 0
roots = set()
for i in range(n):
root = find(i)
if root not in roots:
num_components += 1
roots.add(root)
return num_components