KatInterview

Minimum Deletions to Remove Half the Elements

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsgreedyhashingsorting

Last updated

Tests greedy selection by frequency: choose the fewest distinct values whose total occurrences cover at least half the array.

You are given an array of integers arr. Your task is to select a subset of distinct values from the array and remove every occurrence of each selected value.

Your goal is to remove at least half of the original array elements. Return the minimum number of distinct values you must select to achieve this.

Rules

  • When you select a distinct value, all of its occurrences in the array are removed (you cannot remove only some copies).
  • "At least half" means the number of removed elements must satisfy: 2 × removed_count ≥ len(arr).
    • For arrays with odd length, this means you must remove at least ⌈len(arr) / 2⌉ elements.
    • Example: if len(arr) = 5, you must remove at least 3 elements.
  • Return the count of distinct values selected, not the values themselves.

Constraints

  • 1 ≤ len(arr) ≤ 10⁵
  • -10⁹ ≤ arr[i] ≤ 10⁹

Examples

Example 1

Input: min_deletions_to_remove_half([4, 4, 4, 7, 7, 2, 9, 9])

Output: 2

Example 2

Input: min_deletions_to_remove_half([3, 3, 8, 8, 5])

Output: 2

Example 3

Input: min_deletions_to_remove_half([1, 2, 3, 4, 5, 6])

Output: 3

Hints

Hint 1

Count how many times each distinct value appears in the array. The actual values don't matter, only their frequencies.

Hint 2

To minimize the number of selections, prioritize values that appear most frequently—each selection should remove as many elements as possible.

Hint 3

Sort the frequencies in descending order and greedily pick from the largest until you've removed enough elements to meet the threshold.