Leetcode 1512. Number of Good Pairs
Given an array of integers nums
, return the number of good pairs.
A pair (i, j)
is called good if nums[i] == nums[j]
and i < j
.
Example:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5).
(i, j)
where i < j
and count the number of good pairs.Here is the C++ solution for the optimized approach:
#include <iostream>
#include <vector>
#include <unordered_map>
int numIdenticalPairs(std::vector<int>& nums) {
std::unordered_map<int, int> countMap;
int goodPairs = 0;
for(int num : nums) {
if(countMap.find(num) != countMap.end()) {
goodPairs += countMap[num]; // Increase by the count of previous occurrences of `num`
}
// Update the count of the current number
countMap[num]++;
}
return goodPairs;
}
int main() {
std::vector<int> nums = {1, 2, 3, 1, 1, 3};
std::cout << "Number of good pairs: " << numIdenticalPairs(nums) << std::endl;
return 0;
}
countMap
to store the count of each number.goodPairs
to 0.nums
, we check if it is already in the map.goodPairs
.This approach ensures that we efficiently count the good pairs with a single pass through the array, achieving O(n) time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?