Member-only story
Leetcode 1481: Least Number of Unique Integers after K Removals
2 min readJun 15, 2020
In this Leetcode problem, we try to remove the maximum number of unique integers in an array.
Solution
A couple of ideas for the solution:
- We want to remove the number that appear the least number of times first. That’s the most efficient way of removing the maximum of unique integers.
- To do that we want to build the map
countToNumValues
, which for eachcount
key gives the number of unique integers that appear exactlycount
times in the array - To build
countToNumValues
we use the intermediary mapvalueToCount
, which give for each value in the array the number of times it appears in the array countToNumValues
is a TreeMap, which means the keys are sorted, as we want to tackle the integer with 1, 2, 3 counts in order- We keep track of
leftover
the number of integers we can still remove - When we run out of integers to remove, we add the remaining number to
res
, and returnres
in the end.
class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
Map<Integer, Integer> valueToCount = new HashMap<>();
for (int v : arr) {
valueToCount.put(
v, valueToCount.getOrDefault(v, 0) +…