We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Number of Good Pairs II

Number: 3444

Difficulty: Medium

Paid? No

Companies: Amazon, Meta, Airbus SE


Problem Description

Given two integer arrays nums1 and nums2 and a positive integer k, a pair (i, j) is called good if nums1[i] is divisible by (nums2[j] * k). The task is to return the total number of good pairs.


Key Insights

  • The condition means that for a valid pair, nums1[i] % (nums2[j] * k) should equal 0.
  • Instead of iterating over all possible pairs (which would be inefficient for large arrays), use frequency maps for both arrays.
  • For each distinct number b in nums2, check all multiples of (b * k) present in nums1.
  • Multiples can be generated iteratively, and their frequencies from nums1 can be used to determine the count of good pairs.

Space and Time Complexity

Time Complexity: O(U + (maxA / (b * k)) for each distinct b) where U is the number of unique elements in nums2 and maxA is the maximum value in nums1 (bounded by 10^6). In worst-case this is efficient enough. Space Complexity: O(n + m) for storing frequency counts.


Solution

We first build frequency maps for nums1 and nums2. For every distinct number in nums2, compute step = b * k. If step exceeds the maximum possible value in nums1, skip it. Otherwise, iterate through the multiples of step (i.e., step, 2step, 3step, …) up to 10^6 and add frequencyA[multiple] * frequencyB[b] to the answer. This way, we efficiently count all good pairs without checking each pair explicitly.


Code Solutions

# Python solution with line-by-line comments

def countGoodPairs(nums1, nums2, k):
    # Define the maximum possible value in nums1 (given constraint)
    maxA = 10**6
    # Build frequency map for nums1
    freq1 = {}
    for num in nums1:
        freq1[num] = freq1.get(num, 0) + 1

    # Build frequency map for nums2
    freq2 = {}
    for num in nums2:
        freq2[num] = freq2.get(num, 0) + 1

    count = 0
    # Iterate through each unique number in nums2
    for b, countB in freq2.items():
        step = b * k  # This is the divisor candidate for nums1 elements
        # If step is greater than maxA, no valid nums1 element can be divisible by it
        if step > maxA:
            continue
        # Check each multiple of step up to maxA
        multiple = step
        while multiple <= maxA:
            # Add the product of the frequency in nums1 and the frequency of b in nums2
            count += freq1.get(multiple, 0) * countB
            multiple += step
    return count

# Example usage:
#print(countGoodPairs([1,3,4], [1,3,4], 1))
#print(countGoodPairs([1,2,4,12], [2,4], 3))
← Back to All Questions