Solution: Subarrays with K Different Integers

Let’s solve the Subarrays with K Different Integers problem using the Sliding Window Pattern.

Statement

You are given an integer array nums and an integer k. Your task is to return the number of good subarrays of nums.

A good subarray is a contiguous subarray that contains exactly k distinct integers. For example, in the array [1,2,3,1,2][1, 2, 3, 1, 2], the subarray [1,2,3][1, 2, 3]contains 33 distinct integers: 11, 22, and 33.

Constraints:

  • 11 \leq nums.length 2104\leq 2 * 10^{4}

  • 11 \leq nums[i], k \leq nums.length

Solution

To count the number of subarrays that contain exactly k distinct integers, we use the sliding window pattern. Instead of directly identifying these subarrays, which would be computationally expensive, we calculate the result as the difference between the number of subarrays with at most k distinct integers and the number of subarrays with at most k - 1 distinct integers.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.