992. Subarrays with K Different Integers
Asked at 15Amazon47Microsoft40Bloomberg32Google31Meta12HashedIn90Squarepoint Capital66Roblox55ServiceNow55Infosys45Salesforce41Capital One35Uber30Yandex28TikTok26
Problem
Count the contiguous subarrays of nums that contain exactly k distinct values.
Example: nums = [1,2,1,2,3], k = 2 → 7
Constraints: n ≤ 2·10⁴.
"Exactly k" is not monotonic, but "at most k" is: exactly(k) = atMost(k) − atMost(k−1). atMost counts, for each right end, the r − l + 1 valid windows.
Complexity: O(n).
class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
def at_most(k):
cnt = defaultdict(int)
l = res = 0
for r, x in enumerate(nums):
cnt[x] += 1
while len(cnt) > k:
cnt[nums[l]] -= 1
if cnt[nums[l]] == 0:
del cnt[nums[l]]
l += 1
res += r - l + 1
return res
return at_most(k) - at_most(k - 1)
assert Solution().subarraysWithKDistinct([1, 2, 1, 2, 3], 2) == 7
assert Solution().subarraysWithKDistinct([1, 2, 1, 3, 4], 3) == 3
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
return atMost(nums, k) - atMost(nums, k - 1);
}
private int atMost(int[] nums, int k) {
int[] cnt = new int[nums.length + 1];
int l = 0, distinct = 0, res = 0;
for (int r = 0; r < nums.length; r++) {
if (cnt[nums[r]]++ == 0) distinct++;
while (distinct > k) if (--cnt[nums[l++]] == 0) distinct--;
res += r - l + 1;
}
return res;
}
}
func subarraysWithKDistinct(nums []int, k int) int {
atMost := func(k int) int { // subarrays with at most k distinct values
cnt := map[int]int{}
l, res := 0, 0
for r, x := range nums {
cnt[x]++
for len(cnt) > k {
cnt[nums[l]]--
if cnt[nums[l]] == 0 {
delete(cnt, nums[l])
}
l++
}
res += r - l + 1
}
return res
}
return atMost(k) - atMost(k-1)
}