#3162

Find the Number of Good Pairs I

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(m)
💡

Intuition

Time O(n * m)Space O(m)

Instead of checking each pair, we can use a HashMap to store the frequency of the values in nums2 multiplied by k. This allows us to quickly check how many times each divisor appears, reducing the need for nested loops.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a HashMap to store the frequency of each value in nums2 multiplied by k.
  2. 2Step 2: Loop through nums2 and populate the HashMap with counts.
  3. 3Step 3: Initialize a counter to zero for good pairs.
  4. 4Step 4: Loop through nums1 and for each element, check how many times it can be divided by the keys in the HashMap.
  5. 5Step 5: For each valid division, add the frequency from the HashMap to the counter.
  6. 6Step 6: Return the counter.
solution.py9 lines
1def countGoodPairs(nums1, nums2, k):
2    from collections import Counter
3    freq = Counter(num * k for num in nums2)
4    count = 0
5    for num in nums1:
6        for key in freq:
7            if num % key == 0:
8                count += freq[key]
9    return count

Complexity note: The time complexity is O(n * m) where n is the length of nums1 and m is the length of nums2, due to the nested loops. The space complexity is O(m) because we store the frequency of elements from nums2 in a HashMap.

  • 1Understanding divisibility is crucial for this problem.
  • 2Using a HashMap can significantly reduce the number of checks needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.