Leetcode 3162. Find the Number of Good Pairs I
Given an array of integers nums
, a pair (i, j)
is called good if nums[i] == nums[j]
and i < j
. Write a function to return the number of good pairs in the array.
nums
?nums
array? Are they all integer values?To solve this problem optimally, we can use a hash map (or dictionary) to keep track of the frequency of each number as we iterate through the list.
nums
array:
nums[i]
, all previous identical values nums[j]
(where i > j
) form a good pair.By keeping a frequency map and updating the count of good pairs on the fly, we can efficiently determine the number of good pairs without needing to check every possible pair explicitly.
n
is the length of the array nums
. This is because we are iterating through the array once and using a hash map to store counts.import java.util.HashMap;
public class Solution {
public int numIdenticalPairs(int[] nums) {
// HashMap to store frequency of elements
HashMap<Integer, Integer> freqMap = new HashMap<>();
int goodPairs = 0;
// Iterate through the array
for (int num : nums) {
if (freqMap.containsKey(num)) {
goodPairs += freqMap.get(num);
freqMap.put(num, freqMap.get(num) + 1);
} else {
freqMap.put(num, 1);
}
}
// Return the number of good pairs found
return goodPairs;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3, 1, 1, 3};
System.out.println(solution.numIdenticalPairs(nums)); // Output: 4
}
}
HashMap
named freqMap
to store the frequency of each number as we traverse the array.goodPairs
to 0 to keep count of good pairs.nums
:
freqMap
.goodPairs
and increment its count in the map.goodPairs
.This approach ensures that we correctly count all good pairs efficiently.
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?