- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- Program to find number of sublists that contains exactly k different words in Python
- Count unique sublists within list in Python
- Count number of substrings with exactly k distinct characters in C++
- Program to find number of sublists with sum k in a binary list in Python
- Program to find max values of sublists of size k in Python
- Program to count good meals with exactly two items in Python
- C++ Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
- Sorting array of exactly three unique repeating elements in JavaScript
- Program to count number of elements present in a set of elements with recursive indexing in Python
- Program to find least number of unique integers after K removals using Python
- Program to count number of paths whose sum is k in python
- 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 find sum of unique elements in Python

Advertisements