Lesson 1 · Unit 02
Fixed windows
Slide a window of k items: one in, one out
What you practise
- Add on the right, drop on the left
- O(n) instead of O(nk)
Try a question from this lesson
Pick one
You want the largest sum of 3 neighbours in [5, 1, 6, 2, 9]. The first three sum to 12. What is the cheapest way to get the sum of the next three (1, 6, 2)?
Correct answer
Take 12, subtract the 5, add the 2
Why
The two groups share the 1 and the 6. Only the 5 leaves and the 2 enters, so 12 - 5 + 2 = 9 does it in two steps, however large the group is. Adding from scratch repeats work already done.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Slide, do not recompute
A window of k neighbours slides one step right: one item enters, one leaves. Update the sum with one addition and one subtraction.
That is O(1) per step and O(n) for the whole list, instead of O(n · k) for summing every window from scratch.
def max_window(nums, k):
window = sum(nums[:k])
best = window
for r in range(k, len(nums)):
window += nums[r] - nums[r - k]
best = max(best, window)
return bestfunction maxWindow(nums, k) {
const n = nums.length;
let win = 0;
for (let i = 0; i < k; i++) {
win += nums[i];
}
let best = win;
for (let r = k; r < n; r++) {
win += nums[r] - nums[r - k];
best = Math.max(best, win);
}
return best;
}function maxWindow(
nums: number[],
k: number,
): number {
const n = nums.length;
let win = 0;
for (let i = 0; i < k; i++) {
win += nums[i];
}
let best = win;
for (let r = k; r < n; r++) {
win += nums[r] - nums[r - k];
best = Math.max(best, win);
}
return best;
}Python notenums[:k] is a slice: a new list holding the first k items. sum adds them up.
JavaScript noteJavaScript has no built-in sum, so the first window is added up with a small loop.
TypeScript noteA long signature is wrapped one parameter per line. The trailing comma after the last parameter is allowed and keeps diffs tidy.
10 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 2× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.