Find the longest window with at most K of something, and count windows with exactly K.
The counts map holds exactly the values from left to right, at most K of them distinct, and left is the smallest valid start for right.
Use it when the question asks for the longest stretch, or the number of stretches, with a limit of K on something inside it. Signal words: at most K different, no more than K, exactly K, up to K exceptions, how many stretches.
State: a counts map. Delete a key when its count reaches 0, so the size of the map is the number of distinct values. For "up to K exceptions", one counter of bad values is enough.
Shrink: after each join, while the window holds more than K, the value at left leaves.
Longest: record right − left + 1 after the shrink.
Count: add right − left + 1 after the shrink, in a 64-bit total.
Exactly K: count at most K, then subtract the count for at most K − 1. When K is 0, the answer is 0.
It needs a rule that stays true when a valid window shrinks. Distinct values and bad values have it. Sums with negative values do not.
Cost: each value joins once and leaves at most once, so the pass is O(n).
long in Java and long long in C++; JavaScript numbers are exact up to 2^53, about 9 × 10^15.def longest_at_most_k(values, k):
counts = {}
left = 0
best = 0
for right in range(len(values)):
# [1] The value at right joins: raise its count.
joining = values[right]
counts[joining] = counts.get(joining, 0) + 1
# [2] While the window holds more than k distinct values, the value at left leaves.
while len(counts) > k:
leaving = values[left]
counts[leaving] -= 1
if counts[leaving] == 0:
del counts[leaving] # the size of the map must count only values still in the window
left += 1
# [3] The window is valid again: record its length.
best = max(best, right - left + 1)
return bestpublic int longestAtMostK(int[] values, int k) {
Map<Integer, Integer> counts = new HashMap<>();
int left = 0;
int best = 0;
for (int right = 0; right < values.length; right++) {
// [1] The value at right joins: raise its count.
int joining = values[right];
counts.put(joining, counts.getOrDefault(joining, 0) + 1);
// [2] While the window holds more than k distinct values, the value at left leaves.
while (counts.size() > k) {
int leaving = values[left];
int count = counts.get(leaving) - 1;
if (count == 0) {
counts.remove(leaving); // the size of the map must count only values still in the window
} else {
counts.put(leaving, count);
}
left++;
}
// [3] The window is valid again: record its length.
best = Math.max(best, right - left + 1);
}
return best;
}int longestAtMostK(const vector<int>& values, int k) {
unordered_map<int, int> counts;
int left = 0;
int best = 0;
for (int right = 0; right < (int) values.size(); right++) {
// [1] The value at right joins: raise its count.
int joining = values[right];
counts[joining]++;
// [2] While the window holds more than k distinct values, the value at left leaves.
while ((int) counts.size() > k) {
int leaving = values[left];
if (--counts[leaving] == 0) {
counts.erase(leaving); // the size of the map must count only values still in the window
}
left++;
}
// [3] The window is valid again: record its length.
best = max(best, right - left + 1);
}
return best;
}function longestAtMostK(values, k) {
const counts = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < values.length; right++) {
// [1] The value at right joins: raise its count.
const joining = values[right];
counts.set(joining, (counts.get(joining) || 0) + 1);
// [2] While the window holds more than k distinct values, the value at left leaves.
while (counts.size > k) {
const leaving = values[left];
const count = counts.get(leaving) - 1;
if (count === 0) {
counts.delete(leaving); // the size of the map must count only values still in the window
} else {
counts.set(leaving, count);
}
left++;
}
// [3] The window is valid again: record its length.
best = Math.max(best, right - left + 1);
}
return best;
}def count_at_most_k(values, k):
counts = {}
left = 0
total = 0
for right in range(len(values)):
# [1] The value at right joins: raise its count.
joining = values[right]
counts[joining] = counts.get(joining, 0) + 1
# [2] While the window holds more than k distinct values, the value at left leaves.
while len(counts) > k:
leaving = values[left]
counts[leaving] -= 1
if counts[leaving] == 0:
del counts[leaving]
left += 1
# [3] Every start from left to right gives a valid window that ends at right.
total += right - left + 1
return total
def count_exactly_k(values, k):
# [4] No window of one or more values has 0 distinct values.
if k == 0:
return 0
# [5] Exactly k = at most k, minus at most k - 1.
return count_at_most_k(values, k) - count_at_most_k(values, k - 1)public long countAtMostK(int[] values, int k) {
Map<Integer, Integer> counts = new HashMap<>();
int left = 0;
long total = 0; // 64-bit: 100,000 values have about 5 billion windows
for (int right = 0; right < values.length; right++) {
// [1] The value at right joins: raise its count.
int joining = values[right];
counts.put(joining, counts.getOrDefault(joining, 0) + 1);
// [2] While the window holds more than k distinct values, the value at left leaves.
while (counts.size() > k) {
int leaving = values[left];
int count = counts.get(leaving) - 1;
if (count == 0) {
counts.remove(leaving);
} else {
counts.put(leaving, count);
}
left++;
}
// [3] Every start from left to right gives a valid window that ends at right.
total += right - left + 1;
}
return total;
}
public long countExactlyK(int[] values, int k) {
// [4] No window of one or more values has 0 distinct values.
if (k == 0) {
return 0;
}
// [5] Exactly k = at most k, minus at most k - 1.
return countAtMostK(values, k) - countAtMostK(values, k - 1);
}long long countAtMostK(const vector<int>& values, int k) {
unordered_map<int, int> counts;
int left = 0;
long long total = 0; // 64-bit: 100,000 values have about 5 billion windows
for (int right = 0; right < (int) values.size(); right++) {
// [1] The value at right joins: raise its count.
int joining = values[right];
counts[joining]++;
// [2] While the window holds more than k distinct values, the value at left leaves.
while ((int) counts.size() > k) {
int leaving = values[left];
if (--counts[leaving] == 0) {
counts.erase(leaving);
}
left++;
}
// [3] Every start from left to right gives a valid window that ends at right.
total += right - left + 1;
}
return total;
}
long long countExactlyK(const vector<int>& values, int k) {
// [4] No window of one or more values has 0 distinct values.
if (k == 0) {
return 0;
}
// [5] Exactly k = at most k, minus at most k - 1.
return countAtMostK(values, k) - countAtMostK(values, k - 1);
}function countAtMostK(values, k) {
const counts = new Map();
let left = 0;
let total = 0; // exact up to 2^53, far above the 5 billion windows of 100,000 values
for (let right = 0; right < values.length; right++) {
// [1] The value at right joins: raise its count.
const joining = values[right];
counts.set(joining, (counts.get(joining) || 0) + 1);
// [2] While the window holds more than k distinct values, the value at left leaves.
while (counts.size > k) {
const leaving = values[left];
const count = counts.get(leaving) - 1;
if (count === 0) {
counts.delete(leaving);
} else {
counts.set(leaving, count);
}
left++;
}
// [3] Every start from left to right gives a valid window that ends at right.
total += right - left + 1;
}
return total;
}
function countExactlyK(values, k) {
// [4] No window of one or more values has 0 distinct values.
if (k === 0) {
return 0;
}
// [5] Exactly k = at most k, minus at most k - 1.
return countAtMostK(values, k) - countAtMostK(values, k - 1);
}if len(counts) == k:
total += right - left + 1 # bug: some shorter windows hold fewer than k valuescounts[leaving] -= 1 # bug: the key stays when its count reaches 0
left += 1int total = 0; // bug: 32 bits hold at most 2,147,483,647Your team lead brings a question from the payments team: how many stretches of hours have a net revenue of exactly 6 thousand units? Refunds make some hours negative: [5, -3, 4, 2, -1].
systemdesignmastery.dev/dsa/cheatsheets/at-most-k