Find the Number of Good Pairs I - Problem

You're given two integer arrays nums1 and nums2 with lengths n and m respectively, along with a positive integer k. Your task is to find the total number of good pairs between these arrays.

A pair (i, j) is considered good if:

  • 0 โ‰ค i < n and 0 โ‰ค j < m
  • nums1[i] is divisible by nums2[j] * k

In other words, you need to count how many elements from nums1 are divisible by the product of elements from nums2 and the multiplier k.

Example: If nums1 = [1, 3, 4], nums2 = [1, 3, 4], and k = 1, then pairs like (2, 0) are good because 4 % (1 * 1) = 0.

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*1)=0, (1,1): 3%(3*1)=0, (2,0): 4%(1*1)=0, (2,1): 4%(3*1)โ‰ 0, (2,2): 4%(4*1)=0. Total = 5 pairs.
example_2.py โ€” With Multiplier
$ Input: nums1 = [1, 2, 4, 12], nums2 = [2, 4], k = 3
โ€บ Output: 2
๐Ÿ’ก Note: We check divisibility by nums2[j]*3: nums2*k = [6,12]. Good pairs: (3,0): 12%6=0, (3,1): 12%12=0. Total = 2 pairs.
example_3.py โ€” No Good Pairs
$ Input: nums1 = [1, 2], nums2 = [3, 4], k = 2
โ€บ Output: 0
๐Ÿ’ก Note: nums2*k = [6,8]. Neither 1 nor 2 is divisible by 6 or 8, so no good pairs exist.

Visualization

Tap to expand
Good Pairs Matching GameTeam 1: nums1 = [1, 3, 4]134Team 2: nums2*k = [1, 3, 4]134Compatibility Check Results:1 % 1 = 0 โœ“3 % 3 = 0 โœ“4 % 1 = 0 โœ“4 % 4 = 0 โœ“1 % 3 โ‰  0 โœ—1 % 4 โ‰  0 โœ—3 % 1 โ‰  0 โœ—3 % 4 โ‰  0 โœ—4 % 3 โ‰  0 โœ—Total Good Pairs: 5Pairs: (0,0), (1,1), (2,0), (2,2), plus 1 more
Understanding the Visualization
1
Setup Teams
Team 1 has nums1 players, Team 2 has nums2 players (each multiplied by k)
2
Test Compatibility
Each player from Team 1 tests compatibility with every player from Team 2
3
Count Matches
A match is successful if Team 1 player's number is divisible by Team 2 player's number
4
Total Score
Sum up all successful matches across all possible combinations
Key Takeaway
๐ŸŽฏ Key Insight: For this problem, we must check every possible pairing, making the nested loop approach both simple and optimal with O(nร—m) time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n * m)

We need to check every pair between nums1 (n elements) and nums2 (m elements)

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

Only using a constant amount of extra space for the counter variable

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 50
  • 1 โ‰ค nums1[i], nums2[i] โ‰ค 50
  • 1 โ‰ค k โ‰ค 1000
  • Note: All array elements and k are positive integers
Asked in
Amazon 25 Google 20 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
845 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