
- 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 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 Articles
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- Program to find three unique elements from list whose sum is closest to k Python
- C++ program to find maximum of each k sized contiguous subarray
- Program to find k where k elements have value at least k in Python
- Python program to find N-sized substrings with K distinct characters
- Program to find sum of unique elements in Python
- Python program to find the group sum till each K in a list
- Program to count number of sublists with exactly k unique elements in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find k where given matrix has k by k square of same value in C++
- Program to find any two numbers in a list that sums up to k in Python
- Python program to find probability of getting letter 'a' in some letters and k sized combinations
- Program to find size of each partition of a list where each letter appears at most one piece in Python
- Program to find total unique duration from a list of intervals in Python
- Find top K frequent elements from a list of tuples in Python

Advertisements