← 返回 walmartlabs 的题目列表Remove m Elements to Minimize Unique Count
类型:qbank
Given an integer array and a budget `m`, remove exactly `m` elements such that the number of remaining distinct values is minimized. Return that minimum distinct count.
Requirements
Input: arr: int[], m: int (0 ≤ m ≤ arr.length).
Choose any m positions to delete (order does not matter); minimize |set(remaining)|.
Return the minimum achievable number of distinct values.
Examples
arr = [4, 3, 1, 1, 3, 3, 2], m = 3
→ removing one 4, one 2, and one 1 eliminates values 4 and 2 entirely.
Remaining distinct values: {1, 3} → answer 2.
arr = [2, 1, 1, 3, 3, 3], m = 3
→ removing both 1s and the lone 2 leaves [3,3,3] → answer 1.
Notes
The greedy is: count occurrences per value, then delete entire low-frequency buckets first. Sort the frequency counts ascending and subtract them from m one by one; every bucket fully consumed reduces the distinct count by one. Stop when the next bucket cannot be fully consumed.
Concretely: counts = sorted(Counter(arr).values()); iterate, m -= counts[i]; if m >= 0, distinct -= 1; otherwise stop. Return distinct.
Time O(n + k log k) where k is the distinct count; space O(k).
Two boundary checks to verbalize: m == 0 returns the original distinct count; m == arr.length returns 0 (you can remove everything).
The interviewer in this round followed the coding problem with a multi-file code review, so leave 15-20 minutes on the clock by writing this one efficiently.
Preparation
Write the algorithm twice: once with a counting array (if value range is small) and once with a HashMap + PriorityQueue (general case). The interviewer often asks for the second form after the first works.
Be ready to argue why the greedy is optimal: removing any non-low-frequency element first cannot reduce distinct count more than removing a full low-frequency bucket would.
Cover the LeetCode 1481 family ("Least Number of Unique Integers after K Removals") for warm-up; this Walmart variant is the same skeleton with different wording.