Problem Statement
Pattern:
Solution
public int numIdenticalPairs (int[] nums){
HashMap<Integer, Integer> map = new HashMap<>();
// count how many times has this element been repeated in the past for each repetition.
int totalPrevDuplicates=0;
for (int num : nums) {
int freq = map.getOrDefault(num, 0);
// no. of times num[i] has appeared before added to total
totalPrevDuplicates += freq;
map.put(num, ++freq);
}
return totalPrevDuplicates;
}
Notes
- Its just like the No. of Handshakes Question
- Here instead of no. of handshakes you have to count, how many pairs does each element form with thos in front of it / how many times is an element repeated in front of it
- Or look at it in reverse
Concept
How many elements before this can pair with this element / How many elements before this are duplicates of this element