#3164
Find the Number of Good Pairs II
MediumArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * sqrt(v)) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(n * sqrt(v))Space O(m)
Instead of checking every pair, we can use a HashMap to count occurrences of the required divisors derived from nums2. This allows us to efficiently find how many good pairs can be formed for each element in nums1.
⚙️
Algorithm
4 steps- 1Step 1: Create a HashMap to count occurrences of each value in nums2 divided by k.
- 2Step 2: For each element in nums1, find its divisors up to the square root of the element.
- 3Step 3: For each divisor, check if it exists in the HashMap and add its count to the total good pairs.
- 4Step 4: Return the total count of good pairs.
solution.py14 lines
1def countGoodPairs(nums1, nums2, k):
2 from collections import defaultdict
3 count_map = defaultdict(int)
4 for num in nums2:
5 count_map[num] += 1
6 count = 0
7 for num1 in nums1:
8 for d in range(1, int(num1**0.5) + 1):
9 if num1 % d == 0:
10 if d in count_map:
11 count += count_map[d]
12 if d != num1 // d and (num1 // d) in count_map:
13 count += count_map[num1 // d]
14 return countℹ
Complexity note: The time complexity is O(n * sqrt(v)) where n is the length of nums1 and v is the maximum value in nums1. We loop through nums1 and find divisors, which takes sqrt(v) time. The space complexity is O(m) for storing counts of nums2 in a HashMap.
- 1Understanding divisibility and how to find factors efficiently can greatly reduce the number of operations needed.
- 2Using a HashMap to store counts of elements allows for quick lookups, improving performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.