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.
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5).
Explanation: Each pair in the array are good.
The simplest approach is to check every possible pair (i, j) where 0 <= i < j < nums.length and check if they are equal. If they are, we have found a "good pair."
count to zero to keep track of good pairs.i) goes from 0 to nums.length - 1, and the inner loop (j) runs from i+1 to nums.length - 1.(i, j), check if nums[i] == nums[j]. If yes, increment the count.count after both loops have finished.Instead of comparing pairs directly (which would take O(n²) time), we can count how many times each number appears using a HashMap. Every time we encounter a number we've already seen, it forms a “good pair” with all its previous occurrences.
If a number appears n times, the total number of good pairs formed by that number is:
But rather than using the formula at the end, we can compute pairs incrementally as we traverse the array:
So when we encounter a number again, we simply add its current frequency to the answer.