
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Least Number of Unique Integers After K Removals Using Python
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
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