Reduce Array Size to The Half - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [3,3,3,3,5,5,9,2,8]
›
Output:
2
💡 Note:
We can remove all occurrences of 3 (removes 4 elements) and all occurrences of 5 (removes 2 elements). Total removed: 6 elements ≥ 4 (half of 9). Minimum set size is 2.
Example 2 — Single Element Dominates
$
Input:
arr = [7,7,7,7,7,7]
›
Output:
1
💡 Note:
Remove all occurrences of 7, which removes all 6 elements ≥ 3 (half of 6). Only need 1 element in set.
Example 3 — All Elements Unique
$
Input:
arr = [1,2,3,4]
›
Output:
2
💡 Note:
All elements appear once. Need to remove ≥ 2 elements (half of 4). Must pick any 2 elements, so minimum set size is 2.
Constraints
- 1 ≤ arr.length ≤ 105
- 1 ≤ arr[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
[3,3,3,3,5,5,9,2,8] - need to remove ≥ 4 elements
2
Count & Sort
Frequencies: 3→4, 5→2, others→1 each
3
Greedy Selection
Pick {3,5} removes 6 elements, set size = 2
Key Takeaway
🎯 Key Insight: Always remove the most frequent elements first to minimize the set size needed
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code