Solving Leetcode Interviews in Seconds with AI: Count Array Pairs Divisible by K
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2183" 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
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k. Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 5 Output: 0 Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5. Constraints: 1 <= nums.length <= 105 1 <= nums[i], k <= 105
Explanation
Here's the breakdown of the problem and a Python solution designed for efficiency:
- Core Idea: The key is to avoid explicitly calculating the product
nums[i] * nums[j]for every pair. Instead, we precompute the greatest common divisor (GCD) of each number withkand use these GCDs to determine divisibility more efficiently. - Optimization: We count the occurrences of each GCD and use these counts to calculate the number of pairs satisfying the condition. This avoids redundant GCD calculations.
Efficiency: By using GCDs and counts, we significantly reduce the number of computations, making the solution efficient for large arrays.
Complexity: O(n + sqrt(k)), O(k)
Code
import math
def count_pairs(nums, k):
"""
Counts the number of pairs (i, j) such that 0 <= i < j <= n - 1 and
nums[i] * nums[j] is divisible by k.
Args:
nums: A list of integers.
k: An integer.
Returns:
The number of pairs satisfying the condition.
"""
n = len(nums)
counts = {}
for i in range(n):
gcd_val = math.gcd(nums[i], k)
counts[gcd_val] = counts.get(gcd_val, 0) + 1
ans = 0
gcd_list = list(counts.keys()) # Iterate through unique GCDs for efficiency
for i in range(len(gcd_list)):
for j in range(i, len(gcd_list)):
gcd_i = gcd_list[i]
gcd_j = gcd_list[j]
if (gcd_i * gcd_j) % k == 0:
if i == j:
ans += counts[gcd_i] * (counts[gcd_i] - 1) // 2
else:
ans += counts[gcd_i] * counts[gcd_j]
return ans