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 Subarray INPUT nums array (n=7): 1 i=0 2 i=1 1 i=2 3 i=3 4 i=4 2 i=5 3 i=6 Window size: k = 4 Sliding Windows: [1,2,1,3] -- 3 distinct [2,1,3,4] -- 4 distinct [1,3,4,2] -- 4 distinct [3,4,2,3] -- 3 distinct nums = [1,2,1,3,4,2,3] k = 4 ALGORITHM (Hash Map) 1 Initialize HashMap Store element counts HashMap: {val: count, ...} distinct = map.size() 2 First Window (k=4) Add first k elements {1:2, 2:1, 3:1} = 3 3 Slide Window Remove left, add right -- count[left] ++ count[right] if count=0: delete 4 Record Result ans[i] = map.size() FINAL RESULT Distinct counts per window: 3 i=0 4 i=1 4 i=2 3 i=3 Window Breakdown: [1,2,1,3]: {1,2,3} = 3 [2,1,3,4]: {2,1,3,4} = 4 [1,3,4,2]: {1,3,4,2} = 4 [3,4,2,3]: {3,4,2} = 3 Output: [3, 4, 4, 3] OK - 4 windows processed Time: O(n), Space: O(k) Key Insight: Use a HashMap to track element frequencies in the current window. When sliding the window, decrement the count of the leaving element (remove if 0) and increment the entering element. The HashMap size gives distinct count. This achieves O(n) time instead of O(n*k) brute force. TutorialsPoint - Distinct Numbers in Each Subarray | Hash Map Approach
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