Algo-Sim › Sliding Window
Subarrays with K Different Integers
Hard · Sliding Window · step through it in Java, Python and C++ on your own input
Count subarrays with exactly k distinct values as atMost(k) − atMost(k − 1), with both windows sliding on one shared right edge.
Problem
Given an integer array nums and an integer k, return how many contiguous, non-empty subarrays of nums contain exactly k different values.
Constraints
- 1 ≤ nums.length ≤ 2 · 10⁴
- 1 ≤ nums[i], k ≤ nums.length
Edge cases to test
- k = 1
- k larger than the number of distinct values:
0 - All elements equal
Follow-up questions
- Why does "exactly k" become "at most k − at most k − 1"?
- The at-most windows are monotonic (shrinking never adds a value), so they slide in O(n). "Exactly k" is not, so count it as a difference of two at-most counts.
- Where else does that trick work?
- Any count of subarrays with "exactly k" of a property that is monotonic in window size: e.g. subarrays with exactly k odd numbers (LC 1248).
Solution
Java
public int subarraysWithKDistinct(int[] nums, int k) {
// exactly(k) = atMost(k) - atMost(k - 1), both windows in one pass.
Map<Integer, Integer> wide = new HashMap<>(), narrow = new HashMap<>();
int wideLeft = 0, narrowLeft = 0, total = 0;
for (int right = 0; right < nums.length; right++) {
wide.merge(nums[right], 1, Integer::sum);
narrow.merge(nums[right], 1, Integer::sum);
while (wide.size() > k) {
drop(wide, nums[wideLeft++]);
}
while (narrow.size() > k - 1) {
drop(narrow, nums[narrowLeft++]);
}
total += narrowLeft - wideLeft;
}
return total;
}
private void drop(Map<Integer, Integer> window, int value) {
if (window.merge(value, -1, Integer::sum) == 0) window.remove(value);
}Python
from collections import Counter
def subarrays_with_k_distinct(nums, k):
# exactly(k) = at_most(k) - at_most(k - 1), both windows in one pass.
wide, narrow = Counter(), Counter()
wide_left = narrow_left = total = 0
for right, x in enumerate(nums):
wide[x] += 1
narrow[x] += 1
while len(wide) > k:
drop(wide, nums[wide_left])
wide_left += 1
while len(narrow) > k - 1:
drop(narrow, nums[narrow_left])
narrow_left += 1
total += narrow_left - wide_left
return total
def drop(window, value):
window[value] -= 1
if window[value] == 0:
del window[value]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int subarraysWithKDistinct(vector<int> &nums, int k) {
// exactly(k) = atMost(k) - atMost(k - 1), both windows in one pass.
unordered_map<int, int> wide, narrow;
int wideLeft = 0, narrowLeft = 0, total = 0;
for (int right = 0; right < int(nums.size()); right++) {
wide[nums[right]]++;
narrow[nums[right]]++;
while (int(wide.size()) > k) {
drop(wide, nums[wideLeft++]);
}
while (int(narrow.size()) > k - 1) {
drop(narrow, nums[narrowLeft++]);
}
total += narrowLeft - wideLeft;
}
return total;
}
private:
void drop(unordered_map<int, int> &window, int value) {
if (--window[value] == 0)
window.erase(value);
}
};
More Sliding Window problems
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)