LeetCode 3164: Find the Number of Good Pairs II Solution
Master LeetCode problem 3164 (Find the Number of Good Pairs II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3164. Find the Number of Good Pairs II
Problem Explanation
Explanation
To solve this problem, we iterate through each pair of elements from nums1 and nums2, check if the condition for a good pair is satisfied, and increment the count accordingly. We can optimize this process by creating a HashMap to store the remainders of elements in nums2. This way, we can quickly determine if a pair is good or not using the remainders instead of performing division operations.
- Initialize a HashMap
remainderMapto store the count of remainders innums2. - Iterate over
nums2and calculate the remainders for each element, storing them inremainderMap. - Iterate over each pair of elements from
nums1andnums2, checking if the pair is good based on the remainders inremainderMap. - Increment the count of good pairs accordingly.
Time Complexity
The time complexity of this solution is O(n + m) where n is the length of nums1 and m is the length of nums2.
Space Complexity
The space complexity of this solution is O(m) where m is the length of nums2.
Solution Code
import java.util.HashMap;
class Solution {
public int countGoodPairs(int[] nums1, int[] nums2, int k) {
HashMap<Integer, Integer> remainderMap = new HashMap<>();
for (int num : nums2) {
int remainder = num % k;
remainderMap.put(remainder, remainderMap.getOrDefault(remainder, 0) + 1);
}
int goodPairs = 0;
for (int num : nums1) {
int remainder = num % k;
goodPairs += remainderMap.getOrDefault(0, 0) + remainderMap.getOrDefault(k - remainder, 0);
}
return goodPairs;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3164 (Find the Number of Good Pairs II)?
This page provides optimized solutions for LeetCode problem 3164 (Find the Number of Good Pairs II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3164 (Find the Number of Good Pairs II)?
The time complexity for LeetCode 3164 (Find the Number of Good Pairs II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3164 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3164 in Java, C++, or Python.