Maximum Number of Pairs in Array
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.
nums = [1,3,2,1,3,2,2][3,1]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};
}
Explanation
Pairs are only ever made from equal values, and different values never interact. So the problem decomposes value by value: each distinct number's contribution depends solely on how many times it appears.
We first build a frequency count in one pass. If a value occurs c times, the most pairs we can pull from it is c / 2 (integer division), and whether one copy is left over is exactly c % 2 — odd counts leave a single straggler, even counts leave none.
So we walk the counts once, accumulating pairs += c // 2 and leftover += c % 2. The totals across all values give the final answer with no need to actually simulate removals.
This works because pairing greedily within each value is optimal: there is never a reason to leave two equal copies unpaired, and you can never pair across different values.
Example: [1,3,2,1,3,2,2]. Counts are {1:2, 3:2, 2:3}. From 1 and 3 we get one pair each; from 2 we get one pair and one leftover. Totals: [3, 1].