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

PythonServer Side ProgrammingProgramming

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 −


 Live Demo

def solve(nums, k):
   for num in nums:
      if num not in dictionary:
   for frequency in sorted(dictionary.values()):
         return count
   return count
nums = [5,4,2,2,4,4,3]
k = 3
print(solve(nums, k))


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


Published on 27-May-2021 15:37:35