medium Least Number of Unique Integers after K Removals
Problem Statement
Given an array of integers arr and an integer k, return the least number of unique integers remaining after removing exactly k elements from the array.
Examples
Example 1
- Input:
arr = [5, 5, 4, 3, 2, 3, 2, 3, 3, 2],k = 6 - Expected Output:
1 - Justification: After removing
4, all5, and three instances of2, the updated array will be[3, 3, 3, 3]. It will have only 1 unique element.
Example 2
- Input:
arr = [7, 7, 7, 8, 8, 9],k = 2 - Expected Output:
2 - Justification: Removing two instances of the
8, or 1 instance of8and 1 of9, there will be 2 unique elements in the array.
Example 3
- Input:
arr = [1, 2, 2, 3, 4, 3],k = 4 - Expected Output:
1 - Justification: You can remove
1,4and either both instances of2or3, and the final array will be[2, 2]or[3, 3], based on which element you have removed from the array.
Constraints:
- 1 <= arr.length <= 105
- 1 <= arr[i] <= 109
- 0 <= k <= arr.length
Try it yourself
Try solving this question here:
✅ Solution Least Number of Unique Integers after K Removals
Problem Statement
Given an array of integers arr and an integer k, return the least number of unique integers remaining after removing exactly k elements from the array.
Examples
Example 1
- Input:
arr = [5, 5, 4, 3, 2, 3, 2, 3, 3, 2],k = 6 - Expected Output:
1 - Justification: After removing
4, all5, and three instances of2, the updated array will be[3, 3, 3, 3]. It will have only 1 unique element.
Example 2
- Input:
arr = [7, 7, 7, 8, 8, 9],k = 2 - Expected Output:
2 - Justification: Removing two instances of the
8, or 1 instance of8and 1 of9, there will be 2 unique elements in the array.
Example 3
- Input:
arr = [1, 2, 2, 3, 4, 3],k = 4 - Expected Output:
1 - Justification: You can remove
1,4and either both instances of2or3, and the final array will be[2, 2]or[3, 3], based on which element you have removed from the array.
Constraints:
- 1 <= arr.length <= 105
- 1 <= arr[i] <= 109
- 0 <= k <= arr.length
Solution
To solve this problem, the approach involves tracking the frequency of each integer in the array and then removing the least frequent elements first. This strategy ensures that we maximize the reduction in the number of unique integers. By removing the least frequent elements, we effectively minimize the unique elements left in the array.
The reasoning behind this approach is that removing the least frequent elements impacts the count of unique integers more significantly. This most effective solution ensures that the remaining elements are as few as possible.
Step-by-step Algorithm
-
Frequency Mapping:
- Initialize an empty hash map
elementFrequencyto store the frequency of each element. - Iterate through each element in
arr. - For each element, update the count in
elementFrequencymap.
- Initialize an empty hash map
-
Frequency Counting:
- Initialize an array
frequencyCountof sizen + 1(wherenis the length ofarr) to count the total occurrences of each frequency. - Iterate through the values in
elementFrequencymap. - For each frequency value, increment the corresponding index in
frequencyCountarray.
- Initialize an array
-
Initialize Unique Elements Count:
- Set
uniqueElementsto the size of theelementFrequencymap (number of unique keys), storing total number of unique elements in the given array.
- Set
-
Remove Elements:
- Iterate through possible frequencies from 1 to
n. - For each frequency
i:- Calculate
elementsToRemoveas the minimum ofk // iandfrequencyCount[i]. Here,k//iis the maximum number of elements we can remove which has frequency equal toiwith the remainingkvalue, andfrequencyCount[i]is actual number of elements we can remove, which has a frequency equal toi. for example, if we have3elements with frequency2, and remainingkis4, we can remove only2elements with frequency2. - Decrease
kbyi * elementsToRemove. - Decrease
uniqueElementsbyelementsToRemove. - If
kbecomes less thani, break the loop and returnuniqueElementsas we can't remove more elements.
- Calculate
- Iterate through possible frequencies from 1 to
-
Return Result:
- If all elements are processed, return
uniqueElements.
- If all elements are processed, return
Algorithm Walkthrough
Let's use the Input arr = [5, 5, 4, 3, 2, 3, 2, 3, 3, 2] and k = 6
-
Frequency Mapping:
- Initialize
elementFrequencyas{}. - Iterate through
arr:- Add 5:
elementFrequencybecomes{5: 1}. - Add 5:
elementFrequencybecomes{5: 2}. - Add 4:
elementFrequencybecomes{5: 2, 4: 1}. - Add 3:
elementFrequencybecomes{5: 2, 4: 1, 3: 1}. - Add 2:
elementFrequencybecomes{5: 2, 4: 1, 3: 1, 2: 1}. - Add 3:
elementFrequencybecomes{5: 2, 4: 1, 3: 2, 2: 1}. - Add 2:
elementFrequencybecomes{5: 2, 4: 1, 3: 2, 2: 2}. - Add 3:
elementFrequencybecomes{5: 2, 4: 1, 3: 3, 2: 2}. - Add 3:
elementFrequencybecomes{5: 2, 4: 1, 3: 4, 2: 2}. - Add 2:
elementFrequencybecomes{5: 2, 4: 1, 3: 4, 2: 3}.
- Add 5:
- Initialize
-
Frequency Counting:
- Initialize
frequencyCountas[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]. - Iterate through values in
elementFrequency:- Frequency of 5: increment
frequencyCount[2]to 1. - Frequency of 4: increment
frequencyCount[1]to 1. - Frequency of 3: increment
frequencyCount[4]to 1. - Frequency of 2: increment
frequencyCount[3]to 1.
- Frequency of 5: increment
frequencyCountbecomes[0, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0].
- Initialize
-
Initialize Unique Elements Count:
uniqueElementsis set to the size ofelementFrequencywhich is4.
-
Remove Elements:
- Iterate through frequencies from 1 to
n:- Frequency 1:
elementsToRemove=min(6 // 1, 1)=1.kis decreased by1 * 1=1, sokbecomes5.uniqueElementsis decreased by1, souniqueElementsbecomes3.
- Frequency 2:
elementsToRemove=min(5 // 2, 1)=1.kis decreased by1 * 2=2, sokbecomes3.uniqueElementsis decreased by1, souniqueElementsbecomes2.
- Frequency 3:
elementsToRemove=min(3 // 2, 1)=1.kis decreased by1 * 3=3, sokbecomes0.uniqueElementsis decreased by1, souniqueElementsbecomes1.- Now, K < 3. So, stop iterations, and return
uniqueElements.
- Frequency 1:
- Iterate through frequencies from 1 to
-
Final Result:
- The number of least unique elements is
uniqueElements, which is1.
- The number of least unique elements is
Code
import java.util.*;
public class Solution {
public int reduceUniqueInts(int[] arr, int k) {
// Step 1: Count the frequency of each element
Map<Integer, Integer> elementFrequency = new HashMap<>();
for (int num : arr) {
elementFrequency.put(num, elementFrequency.getOrDefault(num, 0) + 1);
}
int n = arr.length;
// Step 2: Array to count how many elements have a certain frequency
int[] frequencyCount = new int[n + 1];
// Step 3: Fill the frequencyCount array based on elementFrequency map
for (int freq : elementFrequency.values()) {
frequencyCount[freq]++;
}
// Total unique elements
int uniqueElements = elementFrequency.size();
// Step 4: Iterate through possible frequencies and remove elements
for (int i = 1; i <= n; i++) {
int elementsToRemove = Math.min(k / i, frequencyCount[i]);
k -= (i * elementsToRemove);
uniqueElements -= elementsToRemove;
if (k < i) {
return uniqueElements;
}
}
return 0;
}
public static void main(String[] args) {
Solution reducer = new Solution();
System.out.println(
reducer.reduceUniqueInts(new int[] { 5, 5, 4, 3, 2, 3, 2, 3, 3, 2 }, 6)
); // Output: 1
System.out.println(
reducer.reduceUniqueInts(new int[] { 7, 7, 7, 8, 8, 9 }, 2)
); // Output: 2
System.out.println(
reducer.reduceUniqueInts(new int[] { 1, 2, 2, 3, 4, 3 }, 4)
); // Output: 1
}
}
Complexity Analysis
Time Complexity
- We traverse the array
arronce to populate theelementFrequencymap, which takestime, where nis the array length. - We then traverse the
elementFrequencymap to populate thefrequencyCountarray. Since the map can have at mostnentries, this step also takestime. - Finally, we traverse the
frequencyCountarray, which has a size ofn + 1, making this stepas well.
Combining all these steps, the overall time complexity is
Space Complexity
- We create a
elementFrequencymap that can have a maximum ofnentries. - We also create a
frequencyCountarray with a size ofn + 1.
Hence, the total space complexity is
🤖 Don't fully get this? Learn it with Claude
Stuck on Least Number of Unique Integers after K Removals? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Least Number of Unique Integers after K Removals** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Least Number of Unique Integers after K Removals** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Least Number of Unique Integers after K Removals**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Least Number of Unique Integers after K Removals**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.