# Program to find least number of unique integers after K removals using Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array called nums where only integers are stored. If we have a number k. We have to find least number of unique elements after removing exactly k elements.

So, if the input is like nums = [5,4,2,2,4,4,3], k = 3, then the output will be 2, because if we remove 5 and 3, and either any one of 2s or any one of 4s, then there only 2 and 4 will be left.

To solve this, we will follow these steps −

• dictionary:= a new map

• for each num in nums, do

• if num is not in dictionary, then

• dictionary[num]:= 1

• otherwise,

• dictionary[num] := dictionary[num] + 1

• count:= size of dictionary

• for each frequency in the sorted order of all values of dictionary, do

• k := k - frequency

• if k < 0, then

• return count

• otherwise,

• count := count - 1

• return count

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(nums, k):
dictionary={}
for num in nums:
if num not in dictionary:
dictionary[num]=1
else:
dictionary[num]+=1
count=len(dictionary)
for frequency in sorted(dictionary.values()):
k-=frequency
if(k<0):
return count
else:
count-=1
return count
nums = [5,4,2,2,4,4,3]
k = 3
print(solve(nums, k))

## Input

[5,4,2,2,4,4,3], 3

## Output

2