Find the longest window with at most K of something, and count windows with exactly K.
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).
In this lesson you learn to find the longest stretch that holds at most K different values. You also learn to count the stretches with at most K, or exactly K, of them. You keep the counts map from the last lesson, and you let the window grow and shrink.
A music streaming app tags every play with a content category. Category 1 is music, 2 is podcasts and 3 is audiobooks. Your team lead brings two requirements from two teams.
Your team lead says: Recommendations needs the longest session on each channel that touches at most two categories.
Analytics needs how many sessions touch exactly two categories, to see how often listeners mix music and talk.
Both reports run each night over 30 days of every channel, and they must finish within one hour.
Here, a session is any stretch of one or more consecutive plays. Here is a short test history of category ids: [1, 2, 1, 3, 3, 1, 3, 2].
In general the limit is a number K. In this test, K = 2. A session can repeat a category many times. Only the number of different categories counts.
Picture a long shop window with a rule: at most two kinds of item may be on display at once. An assistant places each new item at the right end. She keeps a tally card with one line for each kind on display.
When an item of a third kind arrives, she makes room. She takes items off the left end, oldest first, one at a time. She stops as soon as one kind has no items left. Its line comes off the tally card, and the new kind can go in.
The tally card is the counts map. The number of lines on the card is the number of distinct values. Taking items off the left end until one kind is gone completely is the shrink.
A shop window that may show two kinds of item: add on the right, and when a third kind appears, clear from the left.
Before you write code, solve the test history by hand. It takes three minutes, and it shows you where the work goes.
Solve it by hand: The test history by hand: the longest run with at most two categories. The hand-solve sheet loads in your browser.
You work through it on the whiteboard. You write one row for each start. From each start, you extend the session until a third category would join.
Input: [1, 2, 1, 3, 3, 1, 3, 2], at most K = 2 categories.
| Start | Longest run from this start | Length | Stops at | Sessions from here with exactly 2 |
|---|---|---|---|---|
| 0 | 1, 2, 1 | 3 | index 3 (category 3) | 2 |
| 1 | 2, 1 | 2 | index 3 (category 3) | 1 |
| 2 | 1, 3, 3, 1, 3 | 5 | index 7 (category 2) | 4 |
| 3 | 3, 3, 1, 3 | 4 | index 7 (category 2) | 2 |
| 4 | 3, 1, 3 | 3 | index 7 (category 2) | 2 |
| 5 | 1, 3 | 2 | index 7 (category 2) | 1 |
| 6 | 3, 2 | 2 | the end | 1 |
| 7 | 2 | 1 | the end | 0 |
The longest session is plays 2 to 6, with 5 plays. In the last column, 2 + 1 + 4 + 2 + 2 + 1 + 1 + 0 = 13 sessions touch exactly 2 categories.
Look at starts 2 to 5. All four stop at the same play, index 7, and each one reads again the plays the row above it read. Remember this, because you will use it soon.
You turn the hand method into code.
Start with a correct version. From every start, extend while the session has at most k categories.
def sessions_report(categories, k):
longest = 0
exactly = 0
for start in range(len(categories)):
seen = set()
for end in range(start, len(categories)): # extend this session one play at a time
seen.add(categories[end])
if len(seen) > k:
break
longest = max(longest, end - start + 1)
if len(seen) == k:
exactly += 1
return longest, exactlyThis is correct, and it answers both teams in one pass. For the test history it reads 28 plays, which takes no time at all. The team keeps it as the reference: every faster version must give the same answers.
How much work is it in general? It depends on how far each start can extend. On a channel that never breaks the limit, every start reads to the end of the log. With n plays, that is n + (n − 1) + ... + 1 = n(n + 1) ÷ 2 steps.
Now check the real channels.
Many themed channels stay inside two categories all month. Each one plays about 14,400 tracks in 30 days, and there are 10,000 channels.
Here is the count for the worst night:
Predict the cost
Q A computer does about 10^8 simple operations a second. About how long does the first attempt need for one night?
Answer: C
1.04 × 10^12 ÷ 10^8 = 10,369 seconds, which is about 2.9 hours. The reports must finish within one hour, so the first attempt is about three times too slow.
The first attempt is correct, but on long sessions it cannot keep up. Now the team looks for the work it repeats.
Look at rows 2 to 5 of the hand trace.
Starts 2 to 5 all stop at index 7, and each one reads the same plays again. Can we do better?
The run from start 2 is valid up to index 6. Start 3 sits inside that run. So the run from start 3 is also valid up to index 6, and there is no need to read those plays again.
This works because of one fact. If you remove plays from a session, it can never gain a category. A shorter session inside a valid session is valid too.
So keep one window. Move right one play at a time. Move left only when the window holds K + 1 categories, and never move it backwards. This is the at-most-K window.
The window keeps the counts map from the last lesson: how many plays of each category it holds. As in Windows with counts, you delete a key when its count reaches 0. Then the size of the map is the number of distinct values in the window.
Each step has three parts:
Watch the last step of the test history. At right = 7, category 2 joins, and the map holds three keys: 1: 2, 2: 1, 3: 3.
Index 2 leaves, and category 1 drops to 1. Index 3 and index 4 leave, and category 3 drops to 1. Each time, all three categories are still in the window.
Then index 5 leaves, and category 1 reaches 0. Its key is deleted, and two keys remain. Four plays left, but the loop stopped only when one category was gone completely.
Why is this fast? Each play joins once, when right reaches it. It leaves at most once, when left passes it. So the whole pass makes at most 2n count updates, and it is O(n).
Race: First attempt against the at-most-K window, k = 2. The operation counter loads in your browser.
The race counts the plays each version reads on channel logs with a third category about once in 100 plays. At 100,000 plays, the first attempt reads 11,432,320 plays. The window reads 199,976. On a channel that never breaks the limit, the first attempt would read about 5 × 10^9.
Here is a new log, [7, 4, 4, 7, 9, 4, 9, 9, 4], with K = 2. The player stops at five steps and asks you to predict.
Dry run: Predict the window: at most two distinct values. The step-by-step player loads in your browser.
Reading without the player? Cover the Leaves and Best columns and predict them row by row.
| Right | Joins | Distinct after joining | Leaves while over 2 | Window | Length | Best |
|---|---|---|---|---|---|---|
| 0 | 7 | 1 | none | 0 to 0 | 1 | 1 |
| 1 | 4 | 2 | none | 0 to 1 | 2 | 2 |
| 2 | 4 | 2 | none | 0 to 2 | 3 | 3 |
| 3 | 7 | 2 | none | 0 to 3 | 4 | 4 |
| 4 | 9 | 3 | 7, 4, 4 (indexes 0, 1, 2) | 3 to 4 | 2 | 4 |
| 5 | 4 | 3 | 7 (index 3) | 4 to 5 | 2 | 4 |
| 6 | 9 | 2 | none | 4 to 6 | 3 | 4 |
| 7 | 9 | 2 | none | 4 to 7 | 4 | 4 |
| 8 | 4 | 2 | none | 4 to 8 | 5 | 5 |
Look at right = 4. The first 7 leaves, but another 7 sits at index 3, so the count of 7 only drops to 1. The loop goes on until the count of 4 reaches 0. The longest stretch is 5 values: [9, 4, 9, 9, 4].
One window, left only moves forward: right adds a play, and left removes plays only while there are too many categories.
Now the second request: how many sessions? Start with an easier count, the sessions with at most K categories.
After the shrink, left is the smallest start that works for this right. Every start from left to right works too, because a shorter window inside a valid one is valid. That gives right − left + 1 sessions that end at right.
So add right − left + 1 at every step. On the test history with K = 2, the steps add 1, 2, 3, 2, 3, 4, 5 and 2. That makes 22 sessions with at most 2 categories.
To count sessions, add right minus left plus one at each right: every start from left to right gives a valid session.
Can one window count exactly 2 categories? Look at right = 5 in the test history. These are the sessions that end there:
| Start | Session | Categories |
|---|---|---|
| 0 | 1, 2, 1, 3, 3, 1 | 3 |
| 1 | 2, 1, 3, 3, 1 | 3 |
| 2 | 1, 3, 3, 1 | 2 |
| 3 | 3, 3, 1 | 2 |
| 4 | 3, 1 | 2 |
| 5 | 1 | 1 |
The starts with exactly 2 categories are 2, 3 and 4. They do not run all the way to right. The last session, 1, holds only one category. So the good starts have two edges, and one window keeps only one left edge.
The way out is a subtraction. Every session with at most 2 categories has either exactly 2, or at most 1. So count(exactly 2) = count(at most 2) − count(at most 1). This is exactly K by subtraction: run the counting window twice, with K and with K − 1.
| Right | Joins | At most 2: left | Adds | At most 1: left | Adds | Exactly 2 |
|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 | 1 | 0 |
| 1 | 2 | 0 | 2 | 1 | 1 | 1 |
| 2 | 1 | 0 | 3 | 2 | 1 | 2 |
| 3 | 3 | 2 | 2 | 3 | 1 | 1 |
| 4 | 3 | 2 | 3 | 3 | 2 | 1 |
| 5 | 1 | 2 | 4 | 5 | 1 | 3 |
| 6 | 3 | 2 | 5 | 6 | 1 | 4 |
| 7 | 2 | 6 | 2 | 7 | 1 | 1 |
The totals are 22 and 9, and 22 − 9 = 13. That is the same answer as the hand trace. At right = 5, the two left edges are 2 and 5, and the exactly-2 starts are 2, 3 and 4: the ones in between.
Exactly K equals at most K minus at most K minus one: count both with the same window and subtract.
Here is the rule that keeps this correct. Every line of the templates below exists to protect it.
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.
Why can left never move back? Say the window from left to right holds more than K distinct values. Then every longer window with the same start holds them too. So once the value at left has to leave, no later right can use that start again.
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).
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;
}Rebuild the template: put its lines back in order. Loads in your browser.
The longest-window template: join, shrink while over K deleting keys at zero, then record the length.
The counting pass has the same first two steps. Only the record changes: it adds every valid start instead of keeping the longest. The second function turns two counts into exactly K.
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);
}Step [4] is not only a shortcut. Without it, K = 0 would ask for at most −1 distinct values. No window, not even an empty one, meets that. The shrink loop would try to remove values that are not in the window, and crash.
A chat app stores the sender id of each message in a group thread. The threads team wants to know how much of a thread is a back-and-forth between two members. They ask for the number of stretches of consecutive messages that come from exactly 2 senders. The thread is [5, 8, 5, 8, 3, 3, 8].
This is Template 2 with k = 2. Each row shows where left stops in each pass and what the pass adds.
| Right | Sender | At most 2: left | Adds | At most 1: left | Adds | Exactly 2 |
|---|---|---|---|---|---|---|
| 0 | 5 | 0 | 1 | 0 | 1 | 0 |
| 1 | 8 | 0 | 2 | 1 | 1 | 1 |
| 2 | 5 | 0 | 3 | 2 | 1 | 2 |
| 3 | 8 | 0 | 4 | 3 | 1 | 3 |
| 4 | 3 | 3 | 2 | 4 | 1 | 1 |
| 5 | 3 | 3 | 3 | 4 | 2 | 1 |
| 6 | 8 | 3 | 4 | 6 | 1 | 3 |
The totals are 19 and 8, so the answer is 19 − 8 = 11 stretches. Look at right = 4: sender 3 joins, and left jumps from 0 to 3. Sender 5 leaves at indexes 0 and 2, and only then is its key deleted.
Exercise · Predict the output: At most 2, at most 1, exactly 2. The play categories are below. The code counts the sessions with at most 2 categories, then at most 1, then prints both counts and their difference. What does it print?
values = [3, 1, 3, 2, 2, 3]
totals = []
for k in (2, 1):
counts = {}
left = 0
total = 0
for right in range(len(values)):
counts[values[right]] = counts.get(values[right], 0) + 1
while len(counts) > k:
counts[values[left]] -= 1
if counts[values[left]] == 0:
del counts[values[left]]
left += 1
total += right - left + 1
totals.append(total)
print(totals[0], totals[1], totals[0] - totals[1])Some questions limit bad values, not different values. A music streaming app marks each play with 1 if the listener skipped it and 0 if not. The recommendations team asks for the longest run of plays with at most 1 skip. The flags are [0, 1, 0, 0, 1, 1, 0, 0].
Replace the counts map with one counter, bad. The value at right adds its flag, and while bad is over K, the value at left takes its flag away. Steps [2] and [3] keep their shape. For these flags the answer is 4: the plays 0, 1, 0, 0.
Exercise · Put it in order: The longest run with a few skips. The flags are 1 for a skipped play and 0 for a played one. Arrange the lines into a function that returns the longest run of plays with at most k skips.
def longest_with_exceptions(flags, k):
left, bad, best = 0, 0, 0
for right in range(len(flags)):
bad += flags[right]
while bad > k:
bad -= flags[left]
left += 1
best = max(best, right - left + 1)
return best
if bad > k:long in Java and long long in C++; JavaScript numbers are exact up to 2^53, about 9 × 10^15.Real production data brings edge cases.
A filter asks for sessions with no categories at all: [4, 4] with k = 0. No session of one or more plays has 0 categories.
The longest template returns 0. Every value that joins breaks the limit and leaves at once, so right − left + 1 is 0. The count template returns 0 through step [4], before it ever asks for at most −1.
For [1, 2, 1] with k = 5, the window never shrinks. The longest session is the whole log, 3 plays, and all 6 sessions have at most 5 categories.
Exactly 5 is 6 − 6 = 0, which is correct: no session can touch 5 categories when the log has only 2. Make sure the subtraction gives 0 here and not a negative number.
A music-only channel logs [7, 7, 7, 7]. With k = 1, the longest session is 4 plays.
Every one of its 10 sessions has exactly 1 category. The subtraction agrees: at most 1 gives 10, and at most 0 gives 0, so exactly 1 is 10. On a real channel of 100,000 such plays, the count is 5,000,050,000, which needs the 64-bit total.
A new channel has one play, [3], and k = 1. The window joins index 0, never shrinks, and records length 1. There is 1 session, and it has exactly 1 category.
Check this case. Code that starts the window at two plays, or reads values[right - 1], fails here.
Exercise · Break it: Find the input that crashes the subtraction. This function counts the sessions with exactly k categories as "at most k" minus "at most k - 1". Find an input where it fails or gives the wrong answer.
def count_at_most_k(values, k):
counts = {}
left = 0
total = 0
for right in range(len(values)):
counts[values[right]] = counts.get(values[right], 0) + 1
while len(counts) > k:
counts[values[left]] -= 1
if counts[values[left]] == 0:
del counts[values[left]]
left += 1
total += right - left + 1
return total
def count_exactly_k(values, k):
return count_at_most_k(values, k) - count_at_most_k(values, k - 1)This version keeps one at-most-K window and adds the valid starts only when the window holds exactly K values:
if len(counts) == k:
total += right - left + 1 # bug: some shorter windows hold fewer than k valuesCounterexample: [6, 6, 9, 6] with k = 2. The bug returns 7. The correct answer is 5: [6, 9], [9, 6], [6, 6, 9], [6, 9, 6] and [6, 6, 9, 6].
At right = 2, the window [6, 6, 9] holds 2 values, so the bug adds 3 starts. But the start at index 2 gives [9], with only 1 value. At right = 3 it also counts [6]. The good starts have two edges, so use at most K minus at most K − 1.
Adding starts only when the window holds exactly K counts a session too short, so use at most K minus at most K minus one.
This version of Template 1 lowers the count of the value that leaves, but never deletes its key:
counts[leaving] -= 1 # bug: the key stays when its count reaches 0
left += 1Counterexample: [5, 8, 5, 9] with k = 2. The correct answer is 3, from [5, 8, 5]. The bug never returns an answer at all.
When 9 joins, the map holds three keys. Index 0 leaves, then index 1, and the count of 8 reaches 0. But its key stays, so the map still has three keys. The loop never stops: left runs past right, and Python raises an IndexError at values[4].
This Java version of the count stores the total in an int:
int total = 0; // bug: 32 bits hold at most 2,147,483,647Counterexample: a log of 100,000 plays that are all category 1, with k = 1. The correct count is 5,000,050,000. The 32-bit version returns 705,082,704, which looks like a real answer.
The total first overflows at 65,536 plays, where the true count is 2,147,516,416 and the int holds −2,147,450,880. Any log of 65,536 or more plays where every window is valid breaks it.
Your 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].
Try the subtraction with a sum window: count the stretches with a total of at most 6, minus those with at most 5. It returns 1. The correct answer is 2: [5, -3, 4] and [4, 2].
A shorter stretch inside a valid one can have a larger total, because removing −3 raises it. So the window's rule breaks, and so does the subtraction. Use prefix sums with a hash map instead: count earlier prefix totals equal to the current prefix total minus the target (LeetCode 560: Subarray Sum Equals K).
Your team lead brings five product changes. Each one keeps the window that grows on the right and shrinks on the left.
A parcel-delivery app vans have room for two zone cages. Dispatch wants the longest run of consecutive stops that covers at most two zones. For the zones [4, 4, 7, 4, 2, 2, 7, 2], the answer is 4 stops.
This is Template 1 with k = 2. It is the first practice problem.
A monitoring system can re-run a few failed health checks. On-call wants the longest stretch that is healthy if at most k failures are re-run. For pass, fail, pass, pass, fail, fail, pass, pass, pass, fail with k = 1, the answer is 4.
This is the exceptions form: one counter of failures instead of a counts map. It is the second practice problem.
Analytics wants the exactly-K count for any k, over full 30-day logs. For the categories [2, 2, 4, 2, 5] with k = 2, the answer is 6 sessions.
This is Template 2. On real logs the count passes 2^31, so it needs the 64-bit total. It is the third practice problem.
Editors may replace up to k plays in a session to give it one category. They want the longest session that can become one category. For [2, 2, 5, 2, 5, 5, 5, 2] with k = 1, the answer is 5: replace the 2 inside 5, 2, 5, 5, 5.
The bad values are the plays outside the most common category. So the window is valid while its length minus the largest count in it is at most k (LeetCode 424: Longest Repeating Character Replacement).
A bank app waives fees for a stretch of ledger entries whose fees stay within an allowance. The team wants the number of such stretches. For the fees [3, 1, 4, 1, 5] with an allowance of 5, the answer is 8.
Fees are never negative, so a shorter stretch never costs more. Keep a running total instead of a counts map, and add right − left + 1 at every step, as in Template 2.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you count the stretches with exactly K distinct values in O(n). Say why one window cannot do it. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I grow the window on the right. While it has more than K distinct values, left moves and I delete keys at 0.
After the shrink, every start from left to right is valid, so I add right minus left plus 1 to a 64-bit total.
Exactly K has two edges, so I count at most K and subtract at most K minus 1.
The question asks about stretches with at most K different values, so I would use a variable window with a counts map. The first attempt extends from every start, which is O(n^2) when the stretches are long.
Instead, I move right one step at a time and raise the count of the value that joins. While the map holds more than K keys, the value at left leaves, and I delete its key when its count reaches 0. For the longest stretch, I record right minus left plus 1 after the shrink. Each value joins once and leaves at most once, so this is O(n) time and O(K) space.
To count stretches, I add right minus left plus 1 at every step, in a 64-bit total. Exactly K is at most K minus at most K minus 1, because one window cannot hold both edges. I would test K equal to 0, K above the number of distinct values, and a single value.
Checkpoint · Spot the pattern
Q1/4 Which request is a job for the at-most-K window?
Answer: B
"No more than three" different values over a run of consecutive plays is the signal. The mix question has a fixed size, so it is a fixed window with counts. The other two are not about a stretch.
Q2/4 The log is [3, 3, 6, 3, 8] with K = 2. Value 8 joins at index 4. Where is left when the shrink stops?
Answer: C
Index 0 and index 1 leave, but value 3 is still in the window at index 3. Index 2 leaves, the count of 6 reaches 0, and its key is deleted. Two keys remain, so left stops at 3 (See: the longest session).
Q3/4 A version lowers the count of the value that leaves but never deletes keys at 0. What goes wrong?
Answer: C
The size of the map is the number of distinct values. A key with count 0 keeps the size too high, so the loop never stops (Exhibit 2).
Q4/4 The at-most-K window has a while loop inside a for loop. Why is it O(n), not O(n^2)?
Answer: B
Right moves n times, and left moves forward at most n times across the whole run. That is at most 2n count updates (See: the longest session).
Checkpoint · Counting windows
Q1/4 After the shrink, left is 3 and right is 7. How many windows with at most K distinct values end at right?
Answer: B
Every start from left to right is valid, so the count is right − left + 1 = 7 − 3 + 1 = 5 (See: counting sessions with at most K).
Q2/4 A log has 30 sessions with at most 3 categories and 21 sessions with at most 2. How many have exactly 3?
Answer: B
Every session with at most 3 categories has either exactly 3 or at most 2. So exactly 3 = 30 − 21 = 9 (See: exactly K needs two windows).
Q3/4 A version adds right − left + 1 only when the window holds exactly k values. For [6, 6, 9, 6] with k = 2, what does it return?
Answer: B
It also counts the short windows [9] and [6], which hold only one value. The correct answer is 5. The good starts for exactly K have two edges (Exhibit 1).
Q4/4 What should count_exactly_k([4, 4], 0) return?
Answer: A
No window of one or more values has 0 distinct values, so the answer is 0. The guard also stops the template from asking for at most −1 (Stretch: K is 0).
Checkpoint · Limits and the rule
Q1/2 Which question should NOT be solved with the at-most-K window and the subtraction?
Answer: A
With negative values, a shorter stretch can have a larger total, so the window's rule breaks. Use prefix sums with a hash map instead (Stretch: a net total of exactly K, with refunds).
Q2/2 Which statement is the at-most-K invariant?
Answer: C
Each join updates one count, and the shrink restores the limit before anything is recorded. Left never moves back, because a start that breaks the limit stays broken for every later right.
Ten questions on this lesson. Pass with 80% or more to open the gate to the next stretch on the Academy map.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Longest segment covering at most two zones | Freight | Medium | Template 1 with a counts map, K = 2 |
| 2 | Longest healthy stretch with k re-runs | Observe | Medium | The exceptions form: one counter of failures |
| 3 | Sessions with exactly k categories | Stream | Hard | Counting at most K, the subtraction, 64-bit totals |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.