Subarrays with K Different Integers

HardSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and an integer k, count the contiguous non-empty subarrays that contain exactly k distinct values. Subarrays at different positions are counted separately even if they hold the same values. Return the count. Aim for O(n) time.

Examples

Input: nums = [1,2,1,2,3], k = 2
Output: 7
They are [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], and [1,2,1,2].
Input: nums = [1,2,1,3,4], k = 3
Output: 3
They are [1,2,1,3], [2,1,3], and [1,3,4].

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • 1 <= nums[i] <= nums.length
  • 1 <= k <= nums.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems