Find the Number of Good Pairs II - Problem
Given two integer arrays nums1 and nums2 of lengths n and m respectively, and a positive integer k, you need to find the total number of good pairs.
A pair (i, j) is considered good if nums1[i] is divisible by nums2[j] * k, where 0 โค i < n and 0 โค j < m.
Example: If nums1 = [1, 3, 4], nums2 = [1, 3, 4], and k = 1, then we check each pair to see if nums1[i] % (nums2[j] * k) == 0.
Your task is to efficiently count all such valid pairs and return the total count.
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [1,3,4], nums2 = [1,3,4], k = 1
โบ
Output:
5
๐ก Note:
Good pairs are: (0,0): 1%1=0, (1,0): 3%1=0, (1,1): 3%3=0, (2,0): 4%1=0, (2,2): 4%4=0
example_2.py โ With Multiplier
$
Input:
nums1 = [1,2,4,12], nums2 = [2,4], k = 3
โบ
Output:
2
๐ก Note:
nums2*k = [6,12]. Good pairs: (2,1): 4 is not divisible by 6 or 12, (3,1): 12%12=0. Actually (3,0): 12%6=0 and (3,1): 12%12=0, so answer is 2
example_3.py โ No Valid Pairs
$
Input:
nums1 = [1,3], nums2 = [5,7], k = 2
โบ
Output:
0
๐ก Note:
nums2*k = [10,14]. Neither 1 nor 3 is divisible by 10 or 14, so no good pairs exist
Visualization
Tap to expand
Understanding the Visualization
1
Inventory Count
Count how many boxes of each size and containers of each size we have
2
Divisor Analysis
For each box size, find all container sizes that can fit it perfectly (divisors)
3
Efficient Matching
Multiply the quantities: boxes ร compatible_containers for each match
Key Takeaway
๐ฏ Key Insight: Instead of checking every individual pair, we can group identical values and use mathematical divisor relationships to count valid pairs efficiently, reducing time complexity significantly.
Time & Space Complexity
Time Complexity
O(n + m + U*โV)
Where U is unique values in nums1, V is max value in nums1, n and m are array lengths. We build frequency maps in O(n+m) and then find divisors for each unique value
โ Linear Growth
Space Complexity
O(n + m)
Space for storing frequency maps of both arrays
โก Linearithmic Space
Constraints
- 1 โค nums1.length, nums2.length โค 105
- 1 โค nums1[i], nums2[i] โค 106
- 1 โค k โค 103
- All array elements are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code