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
๐Ÿญ Smart Factory Matching System๐Ÿ“ฆ Boxes (nums1)4ร—26ร—1๐Ÿ“‹ Containers (nums2ร—k)1ร—12ร—24ร—1๐Ÿ” Matching LogicBox size 4 divisors: {1, 2, 4}Matches: 1(ร—1) + 2(ร—2) + 4(ร—1) = 4Box qty: 2, so pairs = 2 ร— 4 = 8Box size 6 divisors: {1, 2, 3, 6}Matches: 1(ร—1) + 2(ร—2) = 3Box qty: 1, so pairs = 1 ร— 3 = 3Total: 8 + 3 = 11 pairs๐Ÿ’ก Key Insight: Group identical items and use math to count efficiently!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n + m)

Space for storing frequency maps of both arrays

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 105
  • 1 โ‰ค nums1[i], nums2[i] โ‰ค 106
  • 1 โ‰ค k โ‰ค 103
  • All array elements are positive integers
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
52.1K Views
Medium-High Frequency
~22 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen