Maximum Number of Pairs in Array

easy array hash map counting

Problem

You are given a 0-indexed integer array nums. In one operation you may pick two equal integers and remove them as a pair. Keep doing this while possible. Return an array answer of length 2 where answer[0] is the number of pairs formed and answer[1] is the number of leftover integers that could not be paired.

Inputnums = [1,3,2,1,3,2,2]
Output[3,1]
Pairs: (1,1), (3,3), (2,2). One extra 2 is left, so 3 pairs and 1 leftover.

def number_of_pairs(nums):
    freq = {}
    for x in nums:
        freq[x] = freq.get(x, 0) + 1
    pairs = leftover = 0
    for c in freq.values():
        pairs += c // 2
        leftover += c % 2
    return [pairs, leftover]
function numberOfPairs(nums) {
  const freq = new Map();
  for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
  let pairs = 0, leftover = 0;
  for (const c of freq.values()) {
    pairs += Math.floor(c / 2);
    leftover += c % 2;
  }
  return [pairs, leftover];
}
class Solution {
    public int[] numberOfPairs(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int x : nums) freq.merge(x, 1, Integer::sum);
        int pairs = 0, leftover = 0;
        for (int c : freq.values()) {
            pairs += c / 2;
            leftover += c % 2;
        }
        return new int[]{pairs, leftover};
    }
}
vector<int> numberOfPairs(vector<int>& nums) {
    unordered_map<int, int> freq;
    for (int x : nums) freq[x]++;
    int pairs = 0, leftover = 0;
    for (auto& p : freq) {
        pairs += p.second / 2;
        leftover += p.second % 2;
    }
    return {pairs, leftover};
}
Time: O(n) Space: O(n)