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
Reduce Array Size to The Half INPUT arr = [3,3,3,3,5,5,9,2,8] 3 3 3 3 5 5 9 2 8 Frequency Count: Value Count 3 4 5 2 9 1 2 1 8 1 Array length: 9 Target removal: 5+ elements ALGORITHM STEPS Greedy Approach 1 Count Frequencies Use hashmap to count each element occurrence 2 Sort by Frequency Sort counts descending: [4, 2, 1, 1, 1] 3 Greedy Selection Pick highest freq first until removed >= n/2 4 Count Set Size Return number of elements selected Execution Trace: Pick 3 (count=4): removed=4 Pick 5 (count=2): removed=6 6 >= 5 (n/2), STOP! Set size = 2 FINAL RESULT Selected Set: {3, 5} Elements Removed: 3 3 3 3 5 5 Remaining (3 elements): 9 2 8 Output: 2 OK - Removed 6 elements (6 >= 9/2 = 4.5) Key Insight: The greedy approach works because removing elements with higher frequencies always reduces the array size faster. By sorting frequencies in descending order and picking greedily, we minimize the set size needed to remove at least n/2 elements. TutorialsPoint - Reduce Array Size to The Half | Greedy Approach
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
156.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen