Distinct Numbers in Each Subarray - Problem

You are given an integer array nums of length n and an integer k. Your task is to find the number of distinct elements in every subarray of size k within nums.

Return an array ans such that ans[i] is the count of distinct elements in nums[i..(i + k - 1)] for each index 0 <= i < n - k.

Example: For nums = [1,2,1,3,4,2,3] and k = 4, the subarrays of size 4 are:

  • [1,2,1,3] → 3 distinct elements
  • [2,1,3,4] → 4 distinct elements
  • [1,3,4,2] → 4 distinct elements
  • [3,4,2,3] → 3 distinct elements

So the answer is [3,4,4,3].

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,3,4,2,3], k = 4
Output: [3,4,4,3]
💡 Note: Subarrays: [1,2,1,3]→3 distinct, [2,1,3,4]→4 distinct, [1,3,4,2]→4 distinct, [3,4,2,3]→3 distinct
Example 2 — Minimum Size
$ Input: nums = [1,2,3], k = 2
Output: [2,2]
💡 Note: Subarrays: [1,2]→2 distinct, [2,3]→2 distinct
Example 3 — All Same Elements
$ Input: nums = [5,5,5,5], k = 3
Output: [1,1]
💡 Note: Subarrays: [5,5,5]→1 distinct, [5,5,5]→1 distinct

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Distinct Numbers in Each SubarrayInput Array:1213423k = 4[1,2,1,3] → 3 distinct[2,1,3,4] → 4 distinct[1,3,4,2] → 4 distinct[3,4,2,3] → 3 distinctOutput Array:3443Each element represents distinct count in corresponding subarray
Understanding the Visualization
1
Input
Array [1,2,1,3,4,2,3] with k=4
2
Process
Count distinct elements in each subarray of size k
3
Output
Array [3,4,4,3] with counts
Key Takeaway
🎯 Key Insight: Use sliding window with frequency tracking to efficiently count distinct elements without recalculation
Asked in
Amazon 25 Microsoft 18 Google 15 Facebook 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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