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
Sliding Window: Distinct Elements CounterArray: [1, 2, 1, 3, 4, 2] with k=3121342Current Window State:Frequency: {1: 2, 2: 1}Distinct Count: 2Window Size k=3Algorithm Steps:1. Initialize frequency map with first k elements2. Record distinct count = map.size()3. Slide window: remove left element, add right element4. Update frequencies and clean zero counts5. Repeat until all subarrays processedWindow Progression Example:Position 0: [1,2,1]{1:2, 2:1} → Count: 2Position 1: [2,1,3]{2:1, 1:1, 3:1} → Count: 3Position 2: [1,3,4]{1:1, 3:1, 4:1} → Count: 3⚡ Efficiency Gain: O(n) vs O(n×k)Each element enters and exits the window exactly once!
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
58.2K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen