Suppose we have a list of numbers called items and another value n. A salesman has items in a bag with random IDs. The salesman can delete as many as n items from the bag. We have to find the minimum number of different IDs in the bag after n removals.
So, if the input is like items = [2, 2, 6, 6] n = 2, then the output will be 1 as we he can sell two items with ID 2 or ID 6, then only items with single target will be there.
To solve this, we will follow these steps:
- c := frequency of each element present in items
- ans := size of c
- freq := sort the list of all frequencies in c
- i := 0
- while i < size of freq, do
- if freq[i] <= n, then
- n := n - freq[i]
- ans := ans - 1
- otherwise,
- return ans
- i := i + 1
- if freq[i] <= n, then
- return 0
Let us see the following implementation to get better understanding:
Example
from collections import Counter class Solution: def solve(self, items, n): c = Counter(items) ans = len(c) freq = sorted(c.values()) i = 0 while i < len(freq): if freq[i] <= n: n -= freq[i] ans -= 1 else: return ans i += 1 return 0 ob = Solution() items = [2, 2, 6, 6] n = 2 print(ob.solve(items, n))
Input
[2, 2, 6, 6], 2
Output
1