Sliding Window Counting windows
185. Subarrays with K Different Integers
You are given an array of integers nums and an integer k. Return the number of subarrays that hold exactly
k different values. A value may appear any number of times, so [3,3,8] holds two different values.
A subarray is a contiguous sequence of elements from nums, with at least one element. Two subarrays are
different if they start or end at different positions, even when they hold the same values.
Example 1
Input: nums = [4, 9, 4, 4, 7], k = 2
7Explanation: Five subarrays hold only 4 and 9: [4,9], [4,9,4], [4,9,4,4], [9,4] and [9,4,4]. Two hold only 4
and 7: [4,7] and [4,4,7].
Example 2
Input: nums = [-1000000000, 7, -1000000000, 7], k = 2
6Explanation: The array holds two values, and every subarray with two or more elements holds both. There are 3 such subarrays of length 2, 2 of length 3 and 1 of length 4.
Example 3
Input: nums = [0, 0, -2, -2, -2], k = 1
9Explanation: A subarray with one value lies inside a run of equal values. The two 0s give 3 subarrays and the three −2s give 6.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ k ≤ nums.length
Clarifying questions
What you would ask an interviewer before writing any code.