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 < nand0 โค j < mnums1[i]is divisible bynums2[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
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)
โ Linear Growth
Space Complexity
O(1)
Only using a constant amount of extra space for the counter variable
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code