Find the Number of Good Pairs II - 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 k=2
$ Input: nums1 = [1,2,4,12], nums2 = [2,4], k = 3
Output: 2
💡 Note: Check divisibility by nums2[j]*k: nums2*3 = [6,12]. Only 12%6=0 and 12%12=0 are valid. Good pairs: (3,0) and (3,1). Total = 2 pairs.
Example 3 — No Valid Pairs
$ Input: nums1 = [1,3], nums2 = [5], k = 2
Output: 0
💡 Note: nums2*k = [10]. Neither 1%10=1 nor 3%10=3 equals 0. No good pairs exist.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • 1 ≤ nums1[i], nums2[i] ≤ 106
  • 1 ≤ k ≤ 103

Visualization

Tap to expand
Find the Number of Good Pairs II INPUT nums1: 1 3 4 n=3 nums2: 1 3 4 m=3 k = 1 Good Pair (i,j): nums1[i] % (nums2[j]*k) == 0 Indices: i in [0,n-1] j in [0,m-1] ALGORITHM (Hash) 1 Build HashMap Count freq of nums2[j]*k 1*1=1: count=1 3*1=3: count=1 4*1=4: count=1 2 Find Divisors For each nums1[i] 3 Check HashMap If divisor in map, add 4 Sum Counts Accumulate good pairs Time: O(n*sqrt(max) + m) Space: O(m) FINAL RESULT Good Pairs Found: (0,0): 1 % (1*1) = 0 [OK] (1,0): 3 % (1*1) = 0 [OK] (1,1): 3 % (3*1) = 0 [OK] (2,0): 4 % (1*1) = 0 [OK] (2,2): 4 % (4*1) = 0 [OK] Other pairs: NOT divisible (0,1): 1%3!=0, (0,2): 1%4!=0 (1,2): 3%4!=0, (2,1): 4%3!=0 Output: 5 Total Good Pairs = 5 Key Insight: Instead of checking all O(n*m) pairs, use a HashMap to store products nums2[j]*k. For each nums1[i], find its divisors and check if they exist in the HashMap. This reduces complexity significantly when nums1 values have few divisors compared to array size. TutorialsPoint - Find the Number of Good Pairs II | Hash Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.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