- 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 find a list of numbers where each K-sized window has unique elements in Python

Suppose we have a list of numbers called nums and another number k, we have to find a list of count of distinct numbers in each window of size k.

So, if the input is like nums = [2, 2, 3, 3, 4], k = 2, then the output will be [1, 2, 1, 2], as the windows are [2, 2], [2, 3], [3, 3], and [3, 4].

To solve this, we will follow these steps −

c := make a dictionary of elements in nums and their frequencies

ans := a new list

for i in range k to size of nums, do

insert size of c at the end of ans

c[nums[i]] := c[nums[i]] + 1

c[nums[i - k]] := c[nums[i - k]] - 1

if c[nums[i - k]] is same as 0, then

remove c[nums[i - k]]

insert size of c at the end of ans

return ans

Let us see the following implementation to get better understanding −

## Example

from collections import Counter class Solution: def solve(self, nums, k): c = Counter() for i in range(k): c[nums[i]] += 1 ans = [] for i in range(k, len(nums)): ans.append(len(c)) c[nums[i]] += 1 c[nums[i - k]] -= 1 if c[nums[i - k]] == 0: del c[nums[i - k]] ans.append(len(c)) return ans ob = Solution() nums = [2, 2, 3, 3, 4] print(ob.solve(nums, 2))

## Input

[2, 2, 3, 3, 4], 2

## Output

[1, 2, 1, 2]

- Related Questions & Answers
- C++ program to find maximum of each k sized contiguous subarray
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- Program to find k where k elements have value at least k in Python
- Program to find three unique elements from list whose sum is closest to k Python
- Program to find k where given matrix has k by k square of same value in C++
- How to find all partitions of a multiset, where each part has distinct elements in JavaScript
- Python program to find the group sum till each K in a list
- Python program to find N-sized substrings with K distinct characters
- Program to find sum of unique elements in Python
- Program to find size of each partition of a list where each letter appears at most one piece in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to count number of sublists with exactly k unique elements in Python
- C++ Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
- Adding K to each element in a Python list of integers
- Assign ids to each unique value in a Python list

Advertisements