PracHub
QuestionsPremiumCoachesLearningGuidesInterview Prep

Quick Overview

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.

  • medium
  • IBM
  • Coding & Algorithms
  • Software Engineer

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.

Input: ([1, 2, 3, 4, 5], 3)

Expected Output: 3

Explanation: All values are unique, so the shortest window with exactly 3 distinct values is any 3 consecutive elements, length 3.

Input: ([5, 5, 5], 1)

Expected Output: 1

Explanation: A single element already has exactly 1 distinct value; trimming duplicates yields length 1.

Input: ([], 1)

Expected Output: -1

Explanation: Empty array — the loop never runs, so no qualifying window exists.

Input: ([7, 7, 7, 7], 0)

Expected Output: -1

Explanation: k = 0 is invalid: any non-empty window has at least one distinct value, so return -1 up front.

Input: ([1, 2, 2, 2, 1, 3], 2)

Expected Output: 2

Explanation: The window [1,2] at the start already has exactly 2 distinct values, length 2.

Input: ([-1, 0, -1, 2, 0], 2)

Expected Output: 2

Explanation: Negative and zero values are handled by equality; the window [-1,0] (and others) gives exactly 2 distinct values, length 2.

Input: ([4, 3, 5, 2, 1], 7)

Expected Output: -1

Explanation: k exceeds the array's distinct count (5), so distinct never reaches 7 — return -1.

Input: ([1, 2, 3, 2, 2, 2, 1], 3)

Expected Output: 3

Explanation: The window [1,2,3] at the start holds all three distinct values {1,2,3}, length 3; no shorter window contains all three.

Input: ([10], 1)

Expected Output: 1

Explanation: A single-element array with k = 1 gives a length-1 window.

Input: ([3, 1, 1, 1, 1, 2], 3)

Expected Output: 6

Explanation: The only value 3 is at index 0 and the only value 2 is at index 5, so the only window containing all of {3,1,2} spans the entire array, length 6.

Hints

  1. 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.
  2. '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.
  3. 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.
Last updated: Jun 26, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,000+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Reverse last two characters with space - IBM (nan)
  • Compute minimum rooms for meeting schedule - IBM (nan)
  • Maximize palindromic strings after character swaps - IBM (medium)
  • Find minimum operations to make array sorted - IBM (easy)
  • Compute shared free time intervals - IBM (Medium)