Number of Good Pairs

easy array hash map math counting

Problem

Return the number of good pairs (i,j) with i < j and nums[i] == nums[j].

Inputnums = [1,2,3,1,1,3]
Output4
Value 1 contributes C(3,2)=3, value 3 contributes C(2,2)=1.

from collections import Counter
def num_identical_pairs(nums):
    return sum(c * (c - 1) // 2 for c in Counter(nums).values())
function numIdenticalPairs(nums) {
  const f = {}; for (const x of nums) f[x] = (f[x] || 0) + 1;
  let ans = 0; for (const c of Object.values(f)) ans += c * (c - 1) / 2;
  return ans;
}
class Solution {
    public int numIdenticalPairs(int[] nums) {
        Map f = new HashMap<>();
        for (int x : nums) f.merge(x, 1, Integer::sum);
        int ans = 0;
        for (int c : f.values()) ans += c * (c - 1) / 2;
        return ans;
    }
}
int numIdenticalPairs(vector& nums) {
    unordered_map f;
    for (int x : nums) f[x]++;
    int ans = 0;
    for (auto& p : f) ans += p.second * (p.second - 1) / 2;
    return ans;
}
Time: O(n) Space: O(n)