Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Remove the single 4, only 5 is left.Example 2:
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.
Constraints:
1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.lengthThis approach involves two main steps. First, count the frequency of each integer in the array. Second, use a min-heap (or priority queue) to remove the integers with the smallest frequency first. This approach ensures that we are removing the least frequent integers to reach the least number of unique integers efficiently.
This C program implements the approach by utilizing an array to keep the frequency of each integer. It then collects these frequencies into another array which is sorted to allow removal of the lowest frequencies first. A loop continues removing these and reducing the count of unique integers. A direct index is maintained to access frequencies in order.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting the frequency array. Space Complexity: O(n) for storing the frequency counts.
This approach takes a greedy strategy to count frequencies of integers and sorts them. By progressively removing elements with smallest frequencies, it directly calculates the least number of unique integers remaining after exactly k removals.
This implementation in C uses a frequency array to count each integer's occurrences. After sorting this array, elements are removed from the smallest frequency upwards until k removals are exhausted.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to the qsort on frequencies. Space Complexity: O(n) for arrays used in frequency counting.
| Approach | Complexity |
|---|---|
| Approach with Frequency Count and Min-Heap | Time Complexity: O(n log n) due to sorting the frequency array. Space Complexity: O(n) for storing the frequency counts. |
| Greedy Approach with Frequency Counting | Time Complexity: O(n log n) due to the qsort on frequencies. Space Complexity: O(n) for arrays used in frequency counting. |
Least Number of Unique Integers after K Removal - Leetcode 1481 - Python • NeetCodeIO • 11,734 views views
Watch 9 more video solutions →Practice Least Number of Unique Integers after K Removals with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor