#2341
Easy Algorithms Maximum number of pairs in array
Array Hash Table Counting
76.0% acceptance
Feb 25, 2026
740
19
You are given a 0-indexed integer array nums. In one operation, you may do the following:
Choose two integers in nums that are equal.
Remove both integers from nums, forming a pair.
The operation is done on nums as many times as possible.
Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn number_of_pairs(nums: Vec<i32>) -> Vec<i32> {
let mut freq = [0i32; 101];
for &n in &nums { freq[n as usize] += 1; }
let pairs: i32 = freq.iter().map(|&f| f / 2).sum();
let leftover: i32 = freq.iter().map(|&f| f % 2).sum();
vec![pairs, leftover]
}
}