The Distinct Numbers in Each Subarray coding problem gives you an array of integers and an integer . You need to return an array of size where each element is the count of unique (distinct) numbers in every contiguous subarray of length .
Amazon frequently asks this question to test a candidate's proficiency with the Sliding Window interview pattern combined with Hash Tables. It evaluation whether you can efficiently update a frequency state as you move through an array. This is a fundamental optimization problem where the goal is to avoid the cost of a nested loop by using linear traversal.
This problem uses a Sliding Window with a Frequency Map.
Array: [1, 2, 1, 3, 4, 2, 3],
Whenever a problem asks for "count of something in all subarrays of size K," think Sliding Window + Hash Map. Practice the logic of "one in, one out" to maintain a running state. If the elements are within a small range (e.g., ), an array of size can be faster than a Hash Map.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sliding Subarray Beauty | Medium | Solve | |
| Maximum Sum of Almost Unique Subarray | Medium | Solve | |
| Count Complete Subarrays in an Array | Medium | Solve | |
| Minimum Consecutive Cards to Pick Up | Medium | Solve | |
| Maximum Erasure Value | Medium | Solve |