Keep a frequency map inside the window to compare stretches with a pattern.
Use it when a window must be compared with a multiset, or the question asks how many of each value, or how many different values, a window holds. Signal words: in any order, same counts, a rearrangement, an anagram, how many different, a window of k.
State a counts map for the window. To compare with a pattern, add a need map for the pattern and a matched counter.
Slide the count of the value at right - k goes down by one; the count of the value at right goes up by one.
Matched change it only when a needed count reaches its need or moves away from it. The window matches when matched equals the number of distinct values in the pattern.
Distinct values delete a key when its count reaches 0. The size of the map is then the number of distinct values in the window.
Cost each value joins once and leaves once, with O(1) average work per hash map update, so the whole pass is O(n + m).
In this lesson you learn to keep a count of each value inside a sliding window. You use it to find every window that holds the same values as a pattern in any order, and to count the different values in every window.
A music streaming app's radio channels shuffle tracks from many curated mixes. When a channel plays every track of one mix back to back, the mix's owner is paid for a full mix. Your team lead sets the requirement.
Your team lead says: Rights holders need every place a channel played a full mix back to back, in any order.
A replay is k consecutive plays that hold exactly the mix's tracks, each as many times as the mix holds it.
Each night the report checks the past 30 days of every channel, and it must finish within one hour.
Here is a short test history of track ids: [2, 7, 7, 5, 7, 2, 7, 2]. The mix is [7, 2, 7], so k = 3. It holds track 7 twice and track 2 once.
A mix is a multiset: order does not matter, but repeats do. So [7, 7, 2] is the same mix, but [2, 7, 2] is not.
Picture a small gallery room that always holds three visitors. At the door, an attendant keeps a tally board with one row for each ticket colour.
When a visitor walks in, she adds one mark to that colour. When a visitor walks out, she rubs out one mark. She never walks into the room to recount.
A tour card says "two red tickets and one blue ticket". To know whether the room holds exactly that group, she compares her board with the card.
The tally board is the counts map. The visitor who walks in is the joiner: one count goes up. The visitor who walks out is the leaver: one count goes down. The tour card is the mix.
A tally board at the door: one mark added for each play that enters, one rubbed out for each that leaves.
Before you write code, check the test history by hand. It takes two minutes, and it shows you where the work goes.
Solve it by hand: The test history by hand: every window of three plays. The hand-solve sheet loads in your browser.
You work through it on the whiteboard. You write one row for each window of 3 plays and count the tracks in it.
Input: the history [2, 7, 7, 5, 7, 2, 7, 2] and the mix [7, 2, 7]. The mix counts are track 2: 1 and track 7: 2.
| Left | Right | Window | Counts | Matches the mix? |
|---|---|---|---|---|
| 0 | 2 | 2, 7, 7 | 2: 1, 7: 2 | Yes |
| 1 | 3 | 7, 7, 5 | 5: 1, 7: 2 | No: track 2 is missing |
| 2 | 4 | 7, 5, 7 | 5: 1, 7: 2 | No: track 5 instead of track 2 |
| 3 | 5 | 5, 7, 2 | 2: 1, 5: 1, 7: 1 | No: track 7 only once |
| 4 | 6 | 7, 2, 7 | 2: 1, 7: 2 | Yes |
| 5 | 7 | 2, 7, 2 | 2: 2, 7: 1 | No: the right tracks, the wrong counts |
The mix was replayed at starts 0 and 4. The window at 5 is a near miss. It holds only tracks 2 and 7, but track 2 appears twice.
Look at two rows in a row. The window loses one play on the left and gains one on the right. Only those two counts change.
You turn the hand method into code.
Start with a correct version. Count the tracks of each window and compare them with the mix's counts.
def count_tracks(tracks):
counts = {}
for track in tracks:
counts[track] = counts.get(track, 0) + 1
return counts
def find_replays(plays, mix):
k = len(mix)
need = count_tracks(mix)
starts = []
for start in range(len(plays) - k + 1):
counts = count_tracks(plays[start:start + k]) # recount the k plays of this window
if counts == need:
starts.append(start)
return startsThis is correct. For the test history it counts 6 windows of 3 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? With n plays and a mix of k tracks, there are n − k + 1 windows. Each window costs k count updates, and then a comparison of two maps. That is about (n − k + 1) × k count updates.
Now check the real report.
A channel plays about 14,400 tracks in 30 days. There are 10,000 channels and 50 featured mixes of 100 tracks each.
Here is the count for one 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's report?
Answer: C
7.15 × 10^11 ÷ 10^8 = 7,150 seconds, which is about 2 hours. The report must finish within one hour, and the map comparisons add more work on top.
The first attempt is correct, but at this size it misses the deadline. Now the team looks for the work it repeats.
Put two neighbouring windows side by side.
Neighbouring windows share k − 1 plays, so only two counts change. Can we do better?
Look at two windows from the test history:
Both windows hold 7, 7. Track 2 leaves, so its count goes from 1 to 0. Track 5 joins, so its count goes from 0 to 1. The count of track 7 does not change.
So do not recount. Keep one counts map for the window. When it slides, lower the count of the play that leaves and raise the count of the play that joins. That is two updates, whether the mix holds 3 tracks or 100.
Sliding the counts: the leaver's count goes down by one and the joiner's goes up by one, whatever the mix size.
There is a second cost. After each slide, the first attempt compares the whole window map with the mix map. A mix of 100 different tracks means up to 100 checks per window. The slide got cheap, but the check did not.
The answer is one more number, called matched. It is the number of distinct mix tracks whose count in the window equals their count in the mix. This number is the matched counter. For the mix [7, 2, 7] there are 2 distinct tracks, so the window is a replay when matched is 2.
You never recompute matched. It changes only on the step where a count reaches its needed value, or leaves it:
Watch it on the last two slides of the test history. Window 3 to 5 holds 5, 7, 2, and matched is 1, because only track 2 has its needed count.
Then track 5 leaves, which is not in the mix, so matched stays 1. Track 7 joins and its count goes from 1 to 2, its needed value, so matched goes up to 2. That is 2 of 2: a replay starts at 4.
Next, track 7 leaves and its count drops from 2 to 1, so matched goes down to 1. Then track 2 joins and its count goes from 1 to 2, past its need of 1. So matched goes down to 0. The near miss [2, 7, 2] is caught without comparing any maps.
Race: First attempt against the sliding counts window, a mix of 100 tracks. The operation counter loads in your browser.
The race counts the count updates of both versions with a mix of 100 tracks. At 100,000 plays, the first attempt does 9,990,200 updates. The sliding counts window does 200,000. The first attempt also compares two maps for every window, which the race does not even count.
Matched counts the tracks at exactly their needed count, so each check is one comparison, not a comparison of two maps.
Exercise · Predict the output: What does matched read on each slide?. The mix is `[7, 2, 2]` and the history is `[2, 7, 2, 2, 7, 7]`. The loop prints matched after each play joins, including the slides where one play leaves. What does it print?
values = [2, 7, 2, 2, 7, 7]
pattern = [7, 2, 2]
k = len(pattern)
need = {}
for value in pattern:
need[value] = need.get(value, 0) + 1
window = {}
matched = 0
seen = []
for right in range(len(values)):
if right >= k:
leaving = values[right - k]
count = window[leaving]
if leaving in need:
if count == need[leaving]:
matched -= 1
elif count == need[leaving] + 1:
matched += 1
window[leaving] = count - 1
joining = values[right]
count = window.get(joining, 0) + 1
window[joining] = count
if joining in need:
if count == need[joining]:
matched += 1
elif count == need[joining] + 1:
matched -= 1
seen.append(matched)
print(*seen)Here is a new history, [6, 4, 4, 4, 1, 4, 6], with the mix [4, 1, 4]. The mix needs track 4 twice and track 1 once, so a replay needs matched = 2. The player stops at five steps and asks you to predict.
Dry run: Predict the counts and matched as the window slides. The step-by-step player loads in your browser.
Reading without the player? Cover the Matched and Replay columns and predict them row by row.
| Window | Leaves | Joins | Count of 4 | Count of 1 | Matched | Replay? |
|---|---|---|---|---|---|---|
| 0 to 2 | none | 6, 4, 4 | 2 | 0 | 1 | No |
| 1 to 3 | 6 | 4 | 3 | 0 | 0 | No |
| 2 to 4 | 4 | 1 | 2 | 1 | 2 | Yes, start 2 |
| 3 to 5 | 4 | 4 | 2 | 1 | 2 | Yes, start 3 |
| 4 to 6 | 4 | 6 | 1 | 1 | 1 | No |
Look at window 1 to 3. Track 4 joins and its count goes from 2 to 3, past its need, so matched drops from 1 to 0. In the next slide a 4 leaves, the count comes back to 2, and matched goes up again. The replays start at 2 and 3.
Here is the rule that keeps this correct. Every line of the templates below exists to protect it.
The counts map holds exactly the plays from left to right, and matched equals the number of mix tracks whose window count equals their count in the mix.
Every slide does two things. The play at the left edge leaves and its count goes down; the play at the right joins and its count goes up. Update matched in the same step as the count it depends on, and the invariant cannot break.
Why is it enough for matched to equal the number of distinct mix tracks? The mix counts add up to k, and the window holds k plays. If every mix track has exactly its count, those k plays are all mix tracks, so no other track fits. A window with a track from outside the mix always leaves some mix track short.
Use it when a window must be compared with a multiset, or the question asks how many of each value, or how many different values, a window holds. Signal words: in any order, same counts, a rearrangement, an anagram, how many different, a window of k.
State: a counts map for the window. To compare with a pattern, add a need map for the pattern and a matched counter.
Slide: the count of the value at right - k goes down by one; the count of the value at right goes up by one.
Matched: change it only when a needed count reaches its need or moves away from it. The window matches when matched equals the number of distinct values in the pattern.
Distinct values: delete a key when its count reaches 0. The size of the map is then the number of distinct values in the window.
Cost: each value joins once and leaves once, with O(1) average work per hash map update, so the whole pass is O(n + m).
The template returns the start of every window that holds the same values as pattern, each as many times, in any order. When the pattern is longer than the data, there is no window, and it returns an empty list.
def find_reorderings(values, pattern):
k = len(pattern)
starts = []
if k > len(values):
return starts
# [1] Count what the pattern needs.
need = {}
for value in pattern:
need[value] = need.get(value, 0) + 1
window = {}
matched = 0
for right in range(len(values)):
# [2] Once the window is full, the value at right - k leaves.
if right >= k:
leaving = values[right - k]
count = window[leaving]
if leaving in need:
if count == need[leaving]:
matched -= 1 # its count is about to drop below the need
elif count == need[leaving] + 1:
matched += 1 # its count is about to come back to the need
window[leaving] = count - 1
# [3] The value at right joins: update its count, then matched.
joining = values[right]
count = window.get(joining, 0) + 1
window[joining] = count
if joining in need:
if count == need[joining]:
matched += 1 # it has reached the need
elif count == need[joining] + 1:
matched -= 1 # it has passed the need
# [4] Every needed value has exactly its count: record the start.
if matched == len(need):
starts.append(right - k + 1)
return startspublic int[] findReorderings(int[] values, int[] pattern) {
int k = pattern.length;
List<Integer> starts = new ArrayList<>();
if (k > values.length) {
return new int[0];
}
// [1] Count what the pattern needs.
Map<Integer, Integer> need = new HashMap<>();
for (int value : pattern) {
need.put(value, need.getOrDefault(value, 0) + 1);
}
Map<Integer, Integer> window = new HashMap<>();
int matched = 0;
for (int right = 0; right < values.length; right++) {
// [2] Once the window is full, the value at right - k leaves.
if (right >= k) {
int leaving = values[right - k];
int count = window.get(leaving);
if (need.containsKey(leaving)) {
if (count == need.get(leaving)) {
matched--; // its count is about to drop below the need
} else if (count == need.get(leaving) + 1) {
matched++; // its count is about to come back to the need
}
}
window.put(leaving, count - 1);
}
// [3] The value at right joins: update its count, then matched.
int joining = values[right];
int count = window.getOrDefault(joining, 0) + 1;
window.put(joining, count);
if (need.containsKey(joining)) {
if (count == need.get(joining)) {
matched++; // it has reached the need
} else if (count == need.get(joining) + 1) {
matched--; // it has passed the need
}
}
// [4] Every needed value has exactly its count: record the start.
if (matched == need.size()) {
starts.add(right - k + 1);
}
}
int[] result = new int[starts.size()];
for (int i = 0; i < result.length; i++) {
result[i] = starts.get(i);
}
return result;
}vector<int> findReorderings(const vector<int>& values, const vector<int>& pattern) {
int k = pattern.size();
vector<int> starts;
if (k > (int) values.size()) {
return starts;
}
// [1] Count what the pattern needs.
unordered_map<int, int> need;
for (int value : pattern) {
need[value]++;
}
unordered_map<int, int> window;
int matched = 0;
for (int right = 0; right < (int) values.size(); right++) {
// [2] Once the window is full, the value at right - k leaves.
if (right >= k) {
int leaving = values[right - k];
int count = window[leaving];
if (need.count(leaving)) {
if (count == need[leaving]) {
matched--; // its count is about to drop below the need
} else if (count == need[leaving] + 1) {
matched++; // its count is about to come back to the need
}
}
window[leaving] = count - 1;
}
// [3] The value at right joins: update its count, then matched.
int joining = values[right];
int count = window[joining] + 1;
window[joining] = count;
if (need.count(joining)) {
if (count == need[joining]) {
matched++; // it has reached the need
} else if (count == need[joining] + 1) {
matched--; // it has passed the need
}
}
// [4] Every needed value has exactly its count: record the start.
if (matched == (int) need.size()) {
starts.push_back(right - k + 1);
}
}
return starts;
}function findReorderings(values, pattern) {
const k = pattern.length;
const starts = [];
if (k > values.length) {
return starts;
}
// [1] Count what the pattern needs.
const need = new Map();
for (const value of pattern) {
need.set(value, (need.get(value) || 0) + 1);
}
const window = new Map();
let matched = 0;
for (let right = 0; right < values.length; right++) {
// [2] Once the window is full, the value at right - k leaves.
if (right >= k) {
const leaving = values[right - k];
const count = window.get(leaving);
if (need.has(leaving)) {
if (count === need.get(leaving)) {
matched--; // its count is about to drop below the need
} else if (count === need.get(leaving) + 1) {
matched++; // its count is about to come back to the need
}
}
window.set(leaving, count - 1);
}
// [3] The value at right joins: update its count, then matched.
const joining = values[right];
const count = (window.get(joining) || 0) + 1;
window.set(joining, count);
if (need.has(joining)) {
if (count === need.get(joining)) {
matched++; // it has reached the need
} else if (count === need.get(joining) + 1) {
matched--; // it has passed the need
}
}
// [4] Every needed value has exactly its count: record the start.
if (matched === need.size) {
starts.push(right - k + 1);
}
}
return starts;
}Rebuild the template: put its lines back in order. Loads in your browser.
Two details are worth a second look. The leave step reads the count before lowering it, so it can tell whether the count was at the need. Template 1 may keep keys with a count of 0, because matched never looks at the size of the map.
The reordering template in four steps: count the need, remove the leaver, add the joiner, then record if matched is full.
Exercise · Find the bug: The mix that is never found. This counts the windows that hold the same tracks as the mix, in any order. It returns 0 for a mix with a repeated track, even when a replay is there. Which line is wrong?
def count_reorderings(values, pattern):
k = len(pattern)
need = {}
for value in pattern:
need[value] = need.get(value, 0) + 1
window, matched, found = {}, 0, 0
for right in range(len(values)):
if right >= k:
leaving = values[right - k]
count = window[leaving]
if leaving in need:
if count == need[leaving]: matched -= 1
elif count == need[leaving] + 1: matched += 1
window[leaving] = count - 1
joining = values[right]
count = window.get(joining, 0) + 1
window[joining] = count
if joining in need:
if count == need[joining]: matched += 1
elif count == need[joining] + 1: matched -= 1
if matched == len(pattern):
found += 1
return foundWhen the question is how many different values each window holds, you need no pattern and no matched counter. The size of the map is the answer, as long as you delete a key when its count reaches 0.
def distinct_counts(values, k):
result = []
window = {}
for right in range(len(values)):
# [1] Once the window is full, the value at right - k leaves.
if right >= k:
leaving = values[right - k]
window[leaving] -= 1
if window[leaving] == 0:
del window[leaving] # a value with no plays left is not in the window
# [2] The value at right joins the window.
joining = values[right]
window[joining] = window.get(joining, 0) + 1
# [3] A full window: the number of keys is the number of distinct values.
if right >= k - 1:
result.append(len(window))
return resultpublic int[] distinctCounts(int[] values, int k) {
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> window = new HashMap<>();
for (int right = 0; right < values.length; right++) {
// [1] Once the window is full, the value at right - k leaves.
if (right >= k) {
int leaving = values[right - k];
window.put(leaving, window.get(leaving) - 1);
if (window.get(leaving) == 0) {
window.remove(leaving); // a value with no plays left is not in the window
}
}
// [2] The value at right joins the window.
int joining = values[right];
window.put(joining, window.getOrDefault(joining, 0) + 1);
// [3] A full window: the number of keys is the number of distinct values.
if (right >= k - 1) {
result.add(window.size());
}
}
int[] out = new int[result.size()];
for (int i = 0; i < out.length; i++) {
out[i] = result.get(i);
}
return out;
}vector<int> distinctCounts(const vector<int>& values, int k) {
vector<int> result;
unordered_map<int, int> window;
for (int right = 0; right < (int) values.size(); right++) {
// [1] Once the window is full, the value at right - k leaves.
if (right >= k) {
int leaving = values[right - k];
window[leaving]--;
if (window[leaving] == 0) {
window.erase(leaving); // a value with no plays left is not in the window
}
}
// [2] The value at right joins the window.
int joining = values[right];
window[joining]++;
// [3] A full window: the number of keys is the number of distinct values.
if (right >= k - 1) {
result.push_back((int) window.size());
}
}
return result;
}function distinctCounts(values, k) {
const result = [];
const window = new Map();
for (let right = 0; right < values.length; right++) {
// [1] Once the window is full, the value at right - k leaves.
if (right >= k) {
const leaving = values[right - k];
window.set(leaving, window.get(leaving) - 1);
if (window.get(leaving) === 0) {
window.delete(leaving); // a value with no plays left is not in the window
}
}
// [2] The value at right joins the window.
const joining = values[right];
window.set(joining, (window.get(joining) || 0) + 1);
// [3] A full window: the number of keys is the number of distinct values.
if (right >= k - 1) {
result.push(window.size);
}
}
return result;
}Exercise · Put it in order: Distinct tracks in the last window. Arrange the lines into a function that slides a window of k plays along the history and returns how many different tracks the last window holds.
def distinct_in_last_window(values, k):
window = {}
for right in range(len(values)):
if right >= k:
leaving = values[right - k]
window[leaving] -= 1
if window[leaving] == 0:
del window[leaving]
window[values[right]] = window.get(values[right], 0) + 1
return len(window)
if right > k:A monitoring system keeps a paging log. For each minute, it records the id of the service that raised that minute's first alert. On-call wants to know how many different services were in trouble in every 5-minute window, to tell one noisy service from a wider incident. The log is [12, 12, 12, 12, 40, 40, 7, 31, 7, 12].
This is Template 2 with k = 5.
| Window | Leaves | Joins | Counts after the slide | Distinct |
|---|---|---|---|---|
| 0 to 4 | none | the first five | 12: 4, 40: 1 | 2 |
| 1 to 5 | 12 | 40 | 12: 3, 40: 2 | 2 |
| 2 to 6 | 12 | 7 | 7: 1, 12: 2, 40: 2 | 3 |
| 3 to 7 | 12 | 31 | 7: 1, 12: 1, 31: 1, 40: 2 | 4 |
| 4 to 8 | 12 | 7 | 7: 2, 31: 1, 40: 2 | 3 |
| 5 to 9 | 40 | 12 | 7: 2, 12: 1, 31: 1, 40: 1 | 4 |
The answer is [2, 2, 3, 4, 3, 4]. Look at window 4 to 8: the last 12 leaves, its count reaches 0, and the key is deleted. Without the delete, the map would still hold four keys and report 4 instead of 3.
Real production data brings edge cases.
A new channel has played only 2 tracks, [4, 9], and the mix is [4, 9, 4]. There is no window of 3 plays at all.
There is nothing to report, so the answer is an empty list, [], not an error. Both templates return [] here. Template 1 stops before it builds any map, and Template 2 never reaches a full window.
The mix [7, 2, 7] needs track 7 twice. The window [2, 7, 2] holds the same two tracks, but it is not a replay.
This is why the need map stores counts, not only the tracks. The matched counter counts track 7 only when its window count is exactly 2.
With the mix [3] and the history [3, 1, 3], every window is one play, so k = 1. The answer is [0, 2].
In each step, one play leaves and the next one joins. When both are the same track, as in [3, 3], its count goes from 1 to 0 and back to 1. The matched counter goes down and up again in the same step, and the window still matches.
With k equal to the length of the history, there is exactly one window, and the leave step never runs.
Track ids are catalogue identifiers, not small numbers. For [1000000000, 7, 1000000000] and the mix [7, 1000000000], the answer is [0, 1].
An array with one slot per possible id would need 10^9 slots, about 4 GB of 32-bit counts. A hash map stores only the ids that appear, so it holds at most k keys for the window.
In the window [7, 5, 7], track 5 is not in the mix [7, 2, 7]. Its count goes up and down in the window map, but it never changes matched.
The window still fails. Its 3 plays include one play that is not a mix track, so track 2 is short and matched stays at 1.
This version checks whether a window holds the same tracks as the mix, ignoring how many times:
if set(plays[start:start + k]) == set(mix): # bug: sets forget repeats
starts.append(start)Counterexample: the test history [2, 7, 7, 5, 7, 2, 7, 2] with the mix [7, 2, 7]. The set version returns [0, 4, 5]. The correct answer is [0, 4].
The window at 5 is [2, 7, 2]. Its set is {2, 7}, the same as the mix's set, but it holds track 2 twice and track 7 once. Repeats are part of the question, so you need counts.
Comparing sets instead of counts forgets repeats: a window with the right tracks but wrong counts looks like a replay.
Comparing two maps feels slow, so this version keeps a running sum of the window and compares it with the sum of the mix:
if window_sum == mix_sum: # bug: different windows can share a sum
starts.append(right - k + 1)Counterexample: the history [1, 4, 2, 3] with the mix [2, 3]. The sum version returns [0, 2]. The correct answer is [2], because [1, 4] also adds up to 5.
Any short fingerprint, such as a sum, a product or a sum of squares, can match for two different windows. A matching fingerprint can only rule a window in for a full check. The matched counter is exact and still O(1) per slide.
This version raises matched each time a mix track joins and lowers it each time one leaves. It reports a window when matched equals k:
if joining in need:
matched += 1 # bug: counts plays of mix tracks, not tracks at their needed countCounterexample: the history [4, 4, 4, 1] with the mix [4, 1, 4]. The bug returns [0, 1]. The correct answer is [1].
The window [4, 4, 4] holds three plays of a mix track, so the bug reports it. But track 4 appears three times and track 1 not at all. The counter must change only when a count reaches its need or moves away from it.
This version of Template 2 lowers the count of the value that leaves, but never deletes the key:
window[leaving] -= 1 # bug: the key stays even when its count is 0Counterexample: [5, 8, 5, 5] with k = 2. The bug returns [2, 2, 2]. The correct answer is [2, 2, 1].
In the last window, [5, 5], track 8 has left and its count is 0. Its key is still in the map, so the map size says 2 different values instead of 1.
Exercise · Break it: Find two groups that share a fingerprint. This counts the windows that are a reordering of the mix by comparing the sum of squares of the window with the sum of squares of the mix. Find a history and a mix where it counts a window that is not a reordering.
def count_reorderings(values, pattern):
k = len(pattern)
target = sum(x * x for x in pattern)
total = 0
found = 0
for right in range(len(values)):
total += values[right] * values[right]
if right >= k:
total -= values[right - k] * values[right - k]
if right >= k - 1 and total == target:
found += 1
return foundYour team lead brings a different question from the rights team: did a channel play the mix's tracks in the mix's order, even with other tracks in between? For the history [7, 5, 2, 9, 7] and the mix [7, 2, 7], the answer is yes: positions 0, 2 and 4.
No window of 3 plays holds the mix, so Template 1 returns []. The plays that matter are spread out, so this is a subsequence, not a window.
Walk the history and the mix with two pointers instead, moving the mix pointer each time its track appears (LeetCode 392: Is Subsequence). The signal to listen for is "back to back". Without it, a window is the wrong tool.
Your team lead brings five product changes. Each one keeps a counts map in the window but changes what it is used for.
The programming team wants to know how varied each stretch of a channel is: the number of different tracks in every window of k plays. For the plays [3, 3, 8, 1, 8] with k = 3, the answer is [2, 3, 2].
This is Template 2 as it stands. It is the first practice problem.
An online store wants a bundle of k consecutive catalogue listings with no product twice, and the largest total price. For the products [3, 5, 3, 8, 5, 9] with prices [40, 25, 30, 20, 35, 15] and k = 3, the first window totals 95, but product 3 appears twice. The best bundle is listings 2 to 4, for 85.
Keep a counts map of product ids and a running total of prices. A window is a valid bundle when the map holds k keys, which needs the delete from Template 2.
A parcel-delivery app loads a batch of parcels in any order, and the team wants to know where the batch passed the scanner. For the batch [4, 9, 4] and the scan stream [9, 4, 6, 4, 9, 4], the only match starts at 3.
This is Template 1 with parcel codes instead of track ids.
The rights team also wants windows where at most one play differs from the mix. For the mix [1, 2, 3, 4] and the history [1, 2, 3, 9, 9, 4, 3, 2, 1], the replay starts at 5, and the windows at 0 and 4 are one play away.
Replace matched with a missing counter: the number of plays the window still lacks. It goes down when a needed track joins below its need, and up when one leaves from at or below it. Report a window when missing is at most 1.
The radio team wants the longest stretch of plays that uses at most two different tracks. For [3, 3, 8, 1, 8, 8, 1], the answer is 5: the plays 8, 1, 8, 8, 1.
Now the window has no fixed size. It grows on the right and shrinks on the left while the map holds more than two keys, with the same delete as Template 2. You build this in the next concept, At most K and exactly K.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find every reordering of a pattern in one pass. Say why a set or a sum is not enough. 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 keep a counts map for the window. Each slide lowers the count of the leaving play and raises the count of the joining play.
Matched counts the mix tracks at exactly their needed count. It changes only when a count reaches its need or moves away from it.
The window is a replay when matched equals the number of distinct mix tracks. Sets forget repeats, and sums can collide.
The question asks for windows that hold the same values as a pattern in any order, so I would use a fixed window with counts. The first attempt counts every window from scratch and compares two maps, which costs about n times k.
Instead, I keep one counts map for the window. When it slides, the value that leaves loses one count and the value that joins gains one.
I also keep matched, the number of distinct pattern values whose window count equals their needed count. It changes only when a count reaches its need or moves away from it, so each slide is constant time. A window matches when matched equals the number of distinct pattern values.
That is O(n + m) time, with space for the distinct values in the pattern and the window. I would not use sets or sums, because repeats and collisions break them. I would test a pattern longer than the data, repeated values, k equal to 1 and k equal to n.
Checkpoint · Spot the pattern
Q1/3 Which request is a job for a fixed window with counts?
Answer: B
"In any order" over 6 consecutive scans is the signal: a fixed window compared with a multiset. The busiest hours need only a running total, and the other two are not about a stretch.
Q2/3 A window of 4 plays has the counts 3: 2, 8: 1, 5: 1. Track 3 leaves and track 5 joins. What are the counts now?
Answer: A
Two counts change: the leaver's goes down by one and the joiner's goes up by one. Track 3 still has one play in the window, so its key stays (See: only two counts change).
Q3/3 The mix needs track 9 twice. In the window, the count of track 9 goes from 2 to 3. What happens to matched?
Answer: B
At 2 the count was at its need, so track 9 counted in matched. At 3 it is past the need, so matched loses it. Matched changes only when a count reaches its need or moves away from it.
Checkpoint · Counts, not shortcuts
Q1/4 A teammate compares the set of each window with the set of the mix [7, 2, 7]. Which window does this version report by mistake?
Answer: C
The set of [2, 7, 2] is {2, 7}, the same as the mix's set, but it holds track 2 twice and track 7 once. Sets forget repeats, so compare counts (Exhibit 1).
Q2/4 A version compares each window's sum with the mix's sum. For the mix [2, 3] and the history [1, 4, 2, 3], what does it return?
Answer: B
The window [1, 4] also adds up to 5. Different windows can share a fingerprint, so the sum version reports start 0 by mistake. The correct answer is [2] (Exhibit 2).
Q3/4 A version of the distinct-values template never deletes a key whose count reaches 0. For [5, 8, 5, 5] with k = 2, what does it return?
Answer: B
In the last window, [5, 5], track 8 has a count of 0, but its key is still in the map. The size says 2 instead of 1. The correct answer is [2, 2, 1] (Exhibit 4).
Q4/4 A new channel has played 2 tracks, [4, 9], and the mix is [4, 9, 4]. What should the reordering template return?
Answer: A
There is no window of 3 plays, so there is nothing to report. For a list of starts, the empty list already means "none" (Stretch: the mix is longer than the history).
Checkpoint · Cost and limits
Q1/3 The history has n plays and the pattern has m values. What is the time of the reordering template?
Answer: B
Counting the pattern takes m steps. Each play joins once and leaves at most once, with O(1) average work per hash map update, so the total is O(n + m). The first attempt is about n × m.
Q2/3 Which question should NOT be solved with a fixed window and counts?
Answer: A
With other tracks in between, the plays are a subsequence, not a window. Walk the history and the mix with two pointers instead.
Q3/3 Which statement is the counts invariant?
Answer: C
Each slide updates the two counts that change and, in the same step, matched. So both parts stay true after every move.
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 | Distinct tracks in every k-play window | Stream | Easy | Fixed window with counts, deleting keys at 0 |
| 2 | Reordered batch in a scan stream | Freight | Medium | Need map, window map and the matched counter |
| 3 | Best bundle of distinct products | Shop | Medium | Counts plus a running total, valid when every value is different |
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.