
- 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 count number of sublists with exactly k unique elements in Python
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
- Related Articles
- Program to find number of sublists that contains exactly k different words in Python
- Count unique sublists within list in Python
- Program to find number of sublists with sum k in a binary list in Python
- Count number of substrings with exactly k distinct characters in C++
- Program to find max values of sublists of size k in Python
- Program to count good meals with exactly two items in Python
- Program to count number of elements present in a set of elements with recursive indexing in Python
- C++ Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
- Program to count number of unique paths that includes given edges in Python
- Python – Elements with factors count less than K
- Program to count number of paths with cost k from start to end point in Python
- Program to count number of paths whose sum is k in python
- Program to find least number of unique integers after K removals using Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find k sublists with largest sums and return sums in ascending order in Python

Advertisements