Problem
Given an array of integersarr and an integer k. Find the least number of unique integers after removing exactly k elements.
Examples
Constraints
- 1 <= arr.length <= 10^5
- 1 <= arr[i] <= 10^9
- 0 <= k <= arr.length
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1481 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1481 # by problem number
lcpy gen -s least_number_of_unique_integers_after_k_removals # by problem name
arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
from collections import Counter
class Solution:
# Time: O(n log n)
# Space: O(n)
def find_least_num_of_unique_ints(self, arr: list[int], k: int) -> int:
counts = sorted(Counter(arr).values())
remaining = len(counts)
for count in counts:
if k < count:
break
k -= count
remaining -= 1
return remaining
| Time | Space |
|---|---|
| O(n log n) | O(n) |