Find minimum subarray length with k distinct integers
Company: IBM
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Given an integer array `arr` and an integer `k`, find the **minimum length** of a contiguous subarray that contains **exactly `k` distinct** integer values.
Return the minimum length, or `-1` if no such subarray exists.
```hint Where to start
Think about a single pass with a **sliding window** plus a hash map from value → count inside the window. The number of map keys is the number of distinct values currently in the window.
```
```hint The "exactly k" trap
"At least `k` distinct" is the easy variant. For **exactly `k`**, once the window holds `k` distinct values, keep shrinking from the left: you can safely drop the leftmost element as long as it's a *duplicate* (its count in the window stays $\geq 1$ after removal). Stop shrinking the moment removing the left element would drop a distinct value (count would hit $0$), then record the window length.
```
```hint Pitfall
When you grow the window and the distinct count exceeds `k`, that window can never be salvaged by adding more elements — you must advance the left pointer until distinct $\leq k$ again. Don't measure length while distinct is $\neq k$.
```
### Constraints & Assumptions
- `arr` can contain duplicate values; values may be any integers (positive, negative, or zero).
- A *subarray* is a **contiguous** slice of the array — not a subsequence.
- "Exactly `k` distinct" means the set of distinct values inside the window has cardinality exactly `k`.
- Aim for $O(n)$ time and $O(n)$ extra space, where $n$ is the length of `arr`.
### Clarifying Questions to Ask
- What should be returned when `k = 0` or when `k` exceeds the total number of distinct values in `arr`? (Likely `-1`, since no qualifying subarray exists.)
- Can `arr` be empty? What is the expected return in that case?
- Is `k` guaranteed to be non-negative, and can it be larger than `len(arr)`?
- Should the answer count a single qualifying window, or is there any tie-breaking requirement beyond "minimum length"?
### What a Strong Answer Covers
- **Correct distinction between "exactly k" and "at most/at least k" distinct** — and an algorithm that shrinks the window only on duplicates so it lands on the *minimum* exactly-`k` window.
- A clean **sliding-window + frequency-map** implementation that is a single left-to-right pass, $O(n)$ time.
- Correct **window-shrink logic**: removing left elements while their in-window count stays positive, stopping before dropping a distinct value, and recording the length only when distinct count equals `k`.
- **Edge cases**: no qualifying subarray (return `-1`), `k = 0`, `k` greater than the array's distinct count, empty array, all-equal elements.
- A clear statement of **time and space complexity** and why the window pointers each move at most $n$ times (amortized linear).
### Follow-up Questions
- How would you adapt the solution to return the **count of all** subarrays with exactly `k` distinct integers, rather than the minimum length? (Hint: `exactly(k) = atMost(k) − atMost(k−1)`.)
- If you instead needed the **maximum length** subarray with exactly `k` distinct, how would the shrink condition change?
- Suppose the array is a **stream** you can only read once and cannot store fully — what part of this approach breaks, and what would you do?
- How would you handle the variant "exactly `k` distinct **and** every value appears at least `m` times"?
Quick Answer: This question tests proficiency with the sliding window technique and hash map-based frequency tracking, applied to subarray problems requiring exact cardinality constraints. It assesses the ability to distinguish between "exactly k distinct" and "at most k distinct" variants — a nuance that reveals depth in algorithmic thinking commonly evaluated in software engineering interviews.
Given an integer array `arr` and an integer `k`, find the **minimum length** of a contiguous subarray that contains **exactly `k` distinct** integer values.
Return the minimum length, or `-1` if no such subarray exists.
**Notes:**
- A *subarray* is a contiguous slice of the array — not a subsequence.
- "Exactly `k` distinct" means the set of distinct values inside the window has cardinality exactly `k`.
- `arr` may contain duplicates and any integers (positive, negative, or zero).
- If `k <= 0`, or `k` exceeds the array's total distinct count, or `arr` is empty, return `-1`.
**Examples:**
- `arr = [1, 2, 1, 2, 3], k = 2` → `2` (e.g. the window `[1, 2]`).
- `arr = [1, 1, 1, 1], k = 2` → `-1` (only one distinct value exists).
- `arr = [5, 5, 5], k = 1` → `1` (a single element already has exactly 1 distinct value).
Aim for `O(n)` time and `O(n)` extra space.
Constraints
- 0 <= len(arr) <= 10^5
- Array values may be any integers (positive, negative, or zero)
- k may be 0 or larger than len(arr); return -1 when no qualifying subarray exists
- Target O(n) time and O(n) extra space
Examples
Input: ([1, 2, 1, 2, 3], 2)
Expected Output: 2
Explanation: Windows like [1,2], [2,1], [1,2] (after sliding off the leading duplicate), and finally [2,3] all hold exactly 2 distinct values; the minimum length is 2.
Input: ([1, 1, 1, 1], 2)
Expected Output: -1
Explanation: Only one distinct value exists, so no window ever reaches 2 distinct values.
Hints
- Use a single left-to-right sliding window with a hash map from value -> count inside the window. The number of map keys with positive count is the current distinct count.
- 'At least k distinct' is easy; for 'exactly k', once the window holds k distinct values keep shrinking from the left as long as the leftmost element is a duplicate (its in-window count stays >= 1 after removal). Stop the moment removing it would drop a distinct value (count would hit 0), then record the length.
- If adding a new element makes distinct exceed k, that window can never qualify by extending right — advance left until distinct <= k again. Only measure length while distinct == k.