#1338
Medium Algorithms Reduce array size to the half
Array Hash Table Greedy Sorting Heap (Priority Queue)
69.3% acceptance
Feb 25, 2026
3362
153
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn min_set_size(arr: Vec<i32>) -> i32 {
let n = arr.len();
let mut freq: std::collections::HashMap<i32, usize> = std::collections::HashMap::new();
for &x in &arr { *freq.entry(x).or_insert(0) += 1; }
let mut counts: Vec<usize> = freq.values().copied().collect();
counts.sort_unstable_by(|a, b| b.cmp(a));
let mut removed = 0;
let mut set_size = 0;
for &c in &counts {
removed += c;
set_size += 1;
if removed * 2 >= n { break; }
}
set_size
}
}