
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to 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
- Related Articles
- Program to find the number of unique integers in a sorted list in Python
- Program to find k partitions after truncating sentence using Python
- Program to find most occurring number after k increments in python
- Program to find number of different integers in a string using Python
- Program to find k where k elements have value at least k in Python
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to count number of sublists with exactly k unique elements in Python
- Program to find largest average of sublist whose size at least k in Python
- Program to find state of prison cells after k days in python
- Program to find longest equivalent sublist after K increments in Python
- Program to find minimum amplitude after deleting K elements in Python
- Program to find number of elements in A are strictly less than at least k elements in B in Python
- Program to find length of longest substring with character count of at least k in Python
- Program to Find Out the Maximum Points From Removals in Python
- Program to Find Out the Cost after Finding k Unique Subsequences From a Given String in C++
