LeetCode 1512: Number of Good Pairs Solution
Master LeetCode problem 1512 (Number of Good Pairs), a easy 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.
1512. Number of Good Pairs
Problem Explanation
Explanation:
To solve this problem, we can iterate through the array and keep track of the count of each number using a hashmap. For each number, if there are k occurrences of that number, we can form k*(k-1)/2 good pairs.
Algorithmic Idea:
- Initialize a hashmap to store the count of each number.
- Iterate through the array and update the count of each number in the hashmap.
- For each number with count
k, increment the total count of good pairs byk*(k-1)/2. - Return the total count of good pairs.
Time Complexity:
The time complexity of this solution is O(N), where N is the number of elements in the input array.
Space Complexity:
The space complexity of this solution is O(N) to store the count of each number in the hashmap.
:
Solution Code
class Solution {
public int numIdenticalPairs(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
int goodPairs = 0;
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
for (int count : countMap.values()) {
goodPairs += count * (count - 1) / 2;
}
return goodPairs;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1512 (Number of Good Pairs)?
This page provides optimized solutions for LeetCode problem 1512 (Number of Good Pairs) 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 1512 (Number of Good Pairs)?
The time complexity for LeetCode 1512 (Number of Good Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1512 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1512 in Java, C++, or Python.