Find the Number of Good Pairs I - Problem

You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k.

A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k (where 0 <= i <= n - 1 and 0 <= j <= m - 1).

Return the total number of good pairs.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,3,4], nums2 = [1,3,4], k = 1
Output: 5
💡 Note: Good pairs: (0,0) since 1%(1*1)=0, (1,0) since 3%(1*1)=0, (1,1) since 3%(3*1)=0, (2,0) since 4%(1*1)=0, (2,2) since 4%(4*1)=0. Total: 5 pairs.
Example 2 — With Multiplier
$ Input: nums1 = [1,2,4,12], nums2 = [2,4], k = 3
Output: 2
💡 Note: We need nums1[i] divisible by nums2[j]*3. Check: 12%(2*3)=0 and 12%(4*3)=0. Only element 12 creates good pairs, giving us 2 total pairs: (3,0) and (3,1).
Example 3 — No Good Pairs
$ Input: nums1 = [1,3], nums2 = [5,7], k = 2
Output: 0
💡 Note: Check divisibility: 1%(5*2)≠0, 1%(7*2)≠0, 3%(5*2)≠0, 3%(7*2)≠0. No elements in nums1 are divisible by any nums2[j]*k, so 0 good pairs.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 50
  • 1 ≤ nums1[i], nums2[j] ≤ 50
  • 1 ≤ k ≤ 1000

Visualization

Tap to expand
Find the Number of Good Pairs I INPUT nums1: 1 3 4 i=0 i=1 i=2 nums2: 1 3 4 j=0 j=1 j=2 k = 1 Good pair (i,j) condition: nums1[i] % (nums2[j]*k) == 0 n = 3, m = 3 ALGORITHM STEPS 1 Build Frequency Map Count occurrences in nums2 freq = {1:1, 3:1, 4:1} Map: value --> count 2 Iterate nums1 For each nums1[i] 3 Check Divisibility Find divisors in freq map For d in freq where nums1[i] % (d*k) == 0: count += freq[d] Add frequency to result 4 Sum All Counts Return total good pairs FINAL RESULT Good Pairs Found: nums1[0]=1: 1%1=0 OK (j=0) nums1[1]=3: 3%1=0 OK (j=0) 3%3=0 OK (j=1) nums1[2]=4: 4%1=0 OK (j=0) 4%4=0 OK (j=2) Pairs: (0,0),(1,0),(1,1), (2,0),(2,2) Total: 1 + 2 + 2 = 5 OUTPUT 5 5 good pairs found Key Insight: Frequency Map Optimization avoids redundant comparisons. Instead of checking each pair O(n*m), we count occurrences of each value in nums2. When nums1[i] is divisible by (d*k), we add the frequency of d directly. This reduces redundant work when nums2 has duplicate values. TutorialsPoint - Find the Number of Good Pairs I | Frequency Map Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~15 min Avg. Time
245 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