Suppose we have a list of numbers called nums and another value k, we have to find the number of sublists required that there are exactly k unique numbers in the sublist.
So, if the input is like nums = [2, 2, 3, 4] k = 2, then the output will be 3, as we have the sublists like: [2, 2, 3], [2, 3], [3, 4].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import Counter class Solution: def solve(self, nums, k): def count(K): slot = Counter() i = res = 0 for j, x in enumerate(nums): slot[x] += 1 while len(slot) > K: slot[nums[i]] -= 1 if slot[nums[i]] == 0: del slot[nums[i]] i += 1 res += j - i + 1 return res return count(k) - count(k - 1) ob = Solution() nums = [2, 2, 3, 4] k = 2 print(ob.solve(nums, k))
[2, 2, 3, 4], 2
3