Program to count number of sublists with exactly k unique elements in Python

PythonServer Side ProgrammingProgramming

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 −

  • Define a function count() . This will take K
  • slot := an empty map, by default all values are 0
  • i := res := 0
  • for each index j, and value x nums, do
    • slot[x] := slot[x] + 1
    • while size of slot > K, do
      • slot[nums[i]] := slot[nums[i]] - 1
      • if slot[nums[i]] is same as 0, then
        • remove slot[nums[i]]
      • i := i + 1
    • res := res + j - i + 1
  • return res
  • From the main method do the following −
  • return count(k) - count(k - 1)

Example (Python)

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))

Input

[2, 2, 3, 4], 2

Output

3
raja
Published on 12-Dec-2020 14:38:47
Advertisements