Distinct Numbers in Each Subarray - Problem
Given an integer array nums of length n and an integer k, you need to analyze every possible contiguous subarray of size k and count how many distinct elements each subarray contains.
Your task is to return an array ans where ans[i] represents the number of unique elements in the subarray starting at index i and ending at index i + k - 1.
For example, if nums = [1, 2, 1, 3, 4] and k = 3, you would examine:
- Subarray
[1, 2, 1]→ 2 distinct elements - Subarray
[2, 1, 3]→ 3 distinct elements - Subarray
[1, 3, 4]→ 3 distinct elements
So the result would be [2, 3, 3].
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1, 2, 1, 3, 4], k = 3
›
Output:
[2, 3, 3]
💡 Note:
Subarray [1,2,1] has 2 distinct elements: {1,2}. Subarray [2,1,3] has 3 distinct elements: {1,2,3}. Subarray [1,3,4] has 3 distinct elements: {1,3,4}.
example_2.py — All Same Elements
$
Input:
nums = [1, 1, 1, 1], k = 2
›
Output:
[1, 1, 1]
💡 Note:
All subarrays of size 2 contain only the element 1, so each has 1 distinct element.
example_3.py — All Different Elements
$
Input:
nums = [1, 2, 3, 4, 5], k = 3
›
Output:
[3, 3, 3]
💡 Note:
Each subarray [1,2,3], [2,3,4], [3,4,5] contains 3 completely different elements.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- 1 ≤ nums[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Set Initial Window
Position the window over the first k elements and count distinct items
2
Slide Window Right
Move window one position: remove leftmost element from frequency count
3
Add New Element
Include the new rightmost element in frequency count
4
Update Counter
The size of frequency map gives us the distinct count
5
Repeat Process
Continue sliding until all subarrays are processed
Key Takeaway
🎯 Key Insight: By maintaining a frequency map and sliding the window efficiently, we avoid recalculating overlapping information. Each element is processed exactly twice (once when entering, once when exiting), achieving optimal O(n) time complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code