Divide Array Into Equal Pairs

easy hash map counting

Problem

You are given an integer array nums that contains exactly 2 * n elements. Decide whether the array can be split into n pairs so that in every pair the two elements are equal. Each element must belong to exactly one pair.

Return true if such a complete pairing exists, otherwise false.

Inputnums = [3, 2, 3, 2, 2, 2]
Outputtrue
Value 3 appears twice → one pair (3, 3). Value 2 appears four times → two pairs (2, 2) and (2, 2). Every value has an even count, so the array splits into 3 equal pairs.

def divide_array(nums):
    count = {}
    for x in nums:
        count[x] = count.get(x, 0) + 1
    for c in count.values():
        if c % 2 != 0:
            return False
    return True
function divideArray(nums) {
  const count = new Map();
  for (const x of nums) {
    count.set(x, (count.get(x) || 0) + 1);
  }
  for (const c of count.values()) {
    if (c % 2 !== 0) return false;
  }
  return true;
}
class Solution {
    public boolean divideArray(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int x : nums) {
            count.put(x, count.getOrDefault(x, 0) + 1);
        }
        for (int c : count.values()) {
            if (c % 2 != 0) return false;
        }
        return true;
    }
}
bool divideArray(vector<int>& nums) {
    unordered_map<int, int> count;
    for (int x : nums) {
        count[x]++;
    }
    for (auto& p : count) {
        if (p.second % 2 != 0) return false;
    }
    return true;
}
Time: O(n) Space: O(n)