Lesson 3 of 4
Fixed-size windows
A window is a block of k items in a row. Instead of adding up every window from scratch, slide it one step at a time, adding the item that enters on the right and subtracting the item that leaves on the left. O(n·k) work becomes O(n).
Count the windows of size k in a list and the additions the direct method makes
Slide a window sum by adding the item that enters and subtracting the item that leaves
Find the item leaving with
right - kand the window's first position withright - k + 1Explain why the slide costs O(n) time and O(1) extra space
Slide other notebooks, such as a count, and spot a notebook that cannot slide
Your sign-up table has one row per day. Here are six days of counts: [2, 1, 5, 1, 3, 2]. The growth team asks a small question: which 3 days in a row had the most sign-ups? In SQL you would reach for a window function. In an interview you write the loop yourself, and the interviewer watches how much work it does.
A window is a block of items that sit next to each other in a list, such as the items at positions 1, 2 and 3. In this lesson every window holds the same number of items, called k, so these are fixed-size windows. With k = 3, our six days hold four windows: positions 0 to 2 hold [2, 1, 5], 1 to 3 hold [1, 5, 1], 2 to 4 hold [5, 1, 3], and 3 to 5 hold [1, 3, 2].
The whole lesson is one move: slide the window one step, add the item that enters, subtract the item that leaves. It turns work that grows like n times k into work that grows like n, where n is the length of the list. The next lesson's windows grow and shrink; these keep their size.
Adding up every window
What does the direct method cost? The plain plan is the brute force, the method that tries every candidate the direct way: for every window, add up its k items from scratch, and keep the largest total. The trace runs that plan on our six days. Two arrows sit under the list: start marks where the current window begins, and i marks the item being added.
Before you step through, guess: how many times does the line total += nums[i] run?
def max_window_sum_slow(nums, k):best = float("-inf")for start in range(len(nums) - k + 1):total = 0for i in range(start, start + k):total += nums[i]best = max(best, total)return best
(nothing printed yet)That count is the cost: n − k + 1 windows, k additions each. The last window starts at position n − k, so the starts run from 0 to n − k, which is n − k + 1 windows. With n = 6 and k = 3 that is 4 × 3 = 12. Now look at what the additions repeat. The first window adds 2, 1 and 5. The second window adds 1 and 5 again, then the new 1. Neighboring windows share k − 1 of their k items, and the direct method adds every shared item again.
The direct method adds up every window from scratch, as in the trace above. On a list of 8 items with k = 3, how many times does the line total += nums[i] run in all? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Slide: one in, one out
How do we stop adding the same items again? Compare the first two windows, [2, 1, 5] and [1, 5, 1]. Moving one step right, exactly one item enters and exactly one item leaves. The 1 at position 3 enters, the 2 at position 0 leaves, and the 1 and 5 stay. So the new sum is the old sum plus the item entering minus the item leaving: 8 + 1 − 2 = 7. That is one addition and one subtraction, whatever k is.
The figure runs this on the same six days. Two pointers, indexes into the list, mark the window's edges: left on its first item and right on its last. Like read and write in the last lesson, both move in the same direction, left to right. The bracket above the cells shows the window's sum, and the bar under them marks the best window so far. Press Next and read the sentence under the figure each time. Before you start, guess how many times each pointer moves in all.
The sum is a notebook, a value we keep up to date as we walk. After the first window it is never added up from scratch: each slide changes it by two numbers. Here are the same moves in Python. The first loop builds the first window. The second loop slides it: right steps onto the item entering, and left points at the item leaving.
Before you step through, guess: when the function returns, which positions do the left and right arrows point at?
def max_window_sum(nums, k):window_sum = 0for right in range(k):window_sum += nums[right]best = window_sumleft = 0for right in range(k, len(nums)):window_sum += nums[right]window_sum -= nums[left]left += 1best = max(best, window_sum)return best
(nothing printed yet)Recap: the first window costs k additions, and each slide after it costs one addition and one subtraction. After every slide, window_sum holds the sum of the k items that end at right. That sentence is the promise of this walk: a fact about the notebook that stays true after every slide. Try the slide on a new list.
Type exactly what this prints, one line per print. nums[a:b] is the slice from position a up to, but not including, position b, and print puts one space between its two values.
nums = [3, 1, 4, 1, 5]
k = 2
window_sum = nums[0] + nums[1]
print(nums[0:2], window_sum)
left = 0
for right in range(k, len(nums)):
window_sum += nums[right]
window_sum -= nums[left]
left += 1
print(nums[left:right + 1], window_sum)
Where the window starts and ends
Which positions are inside the window, and which item leaves? Off-by-one mistakes live at a window's edges, so we pin the positions down once. The table follows the trace above, one row per slide.
right | enters | leaves | window after the slide | window_sum |
|---|---|---|---|---|
| first window | none | none | positions 0 to 2: [2, 1, 5] | 8 |
| 3 | 1 | 2, at position 0 | positions 1 to 3: [1, 5, 1] | 7 |
| 4 | 3 | 1, at position 1 | positions 2 to 4: [5, 1, 3] | 9 |
| 5 | 2 | 5, at position 2 | positions 3 to 5: [1, 3, 2] | 6 |
Read down the columns and three rules appear:
- The item leaving sits at
right - k. Whenrightis 3 it is at 0, and whenrightis 5 it is at 2. In the trace,leftheld exactly that value each time we subtracted. - The window that ends at
rightstarts atright - k + 1. It holds positionsright - k + 1throughright, which is k items. rightruns from k to n − 1, which isrange(k, len(nums)). That is n − k slides, plus the first window: n − k + 1 windows, the same count as the direct method.
At the moment we subtract, left always equals right - k, so left can be computed instead of stored. Most solutions you will read, including the problem later in this lesson, write nums[right - k] and drop the name left.
This version drops the name left. The window holds k items, and line 2 has added the item at right. Which line belongs in the gap, to subtract the item that leaves?
for right in range(k, len(nums)):
window_sum += nums[right]
# the missing line
best = max(best, window_sum)Choose one answer, then check.
One more shortcut: sum(nums[:k]) adds up the first window in one line. nums[:k] is a slice with no number before the colon, so it starts at 0: a new list holding a copy of the first k items. For a moment that copy uses O(k) extra space; the build loop in the trace avoids it. Put the short version together.
Put the lines in order to build max_window_sum(nums, k), which returns the largest sum of any k items in a row. Each slide must do one addition and one subtraction, not add the window up again. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
window_sum = sum(nums[right - k + 1:right + 1])def max_window_sum(nums, k):return bestwindow_sum = sum(nums[:k])for right in range(k, len(nums)):best = window_sumbest = 0best = max(best, window_sum)window_sum += nums[right] - nums[right - k]
Many interview rounds have no run button, so you check your own code by tracing it by hand. Negative numbers are where hand traces slip, because subtracting a negative number adds.
On paper, trace this function on nums = [-2, -5, -1, -3] with k = 2. Make a table with one row per slide and the columns right, entering, leaving, window_sum and best. Then check the answer by listing every window's sum.
def max_window_sum(nums, k):
window_sum = sum(nums[:k])
best = window_sum
for right in range(k, len(nums)):
window_sum += nums[right] - nums[right - k]
best = max(best, window_sum)
return bestWork it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
What the slide saves
How much work does sliding save? Count the additions and subtractions. The first window costs k additions, and each of the n − k slides costs one addition and one subtraction: k + 2 × (n − k) in all. For our six days that is 3 + 2 × 3 = 9, the same 9 pointer moves the figure counted. The direct method made 12 additions.
Twelve against nine is not much. The gap opens as the list grows:
| n | k | add every window: (n − k + 1) × k | slide: k + 2 × (n − k) |
|---|---|---|---|
| 6 | 3 | 12 | 9 |
| 1,000 | 100 | 90,100 | 1,900 |
| 100,000 | 50,000 | 2,500,050,000 | 150,000 |
The slide does at most two operations per item, so it costs O(n) time. O(n) means the work grows in step with the length of the list (module 2). The brute force costs O(n·k), work that grows like n times k, and when k is about half of n that is about n2/4 additions, which is O(n2). The slide keeps four numbers (window_sum, best, left and right) whatever the size of the list, so it uses O(1) extra space.
A list has n items and the window holds k of them, with k at most n. The sliding version builds the first window with k additions, then makes one addition and one subtraction per slide. What is its time cost?
Choose one answer, then check.
Here is the pattern in the four questions this course asks of every algorithm:
Now the full problem. It asks for the largest average instead of the largest sum. An average is the sum divided by the number of items, here k. Every window holds exactly k items, so the window with the largest sum also has the largest average. Keep whole-number sums in the notebook and divide once at the end, with /: it always gives a float (a number with a decimal point), while // rounds down (3 // 2 is 1, but the average of [1, 2] is 1.5).
Two details decide that problem. First, best starts at the first window's sum. In the all-negative example every window sum is below 0, so a best started at 0 would never change and the answer would be 0.0, the average of no window at all. Second, when k equals the length there is one window, and the sliding loop runs zero times; nothing special is needed. The speed test uses 100,000 items and k = 20,000, where adding every window from scratch would be about 1.6 billion additions.
A window that counts
Does the notebook have to be a sum? No. A window slides whenever its notebook can be updated in one step as one item enters and one item leaves. A count is the next simplest. Here is a question about letters: what is the largest number of vowels in any 3 letters in a row of "banana"? The notebook is count, the number of vowels inside the window. A letter entering adds 1 only if it is a vowel, and a letter leaving subtracts 1 only if it was a vowel. The test s[right] in "aeiou" is True when the letter is one of those five vowels.
The trace draws the string as a row of cells, with the right arrow under the letter entering. The letter leaving is at right - k, as before. Before you step through, guess the answer.
def most_vowels(s, k):count = 0for right in range(k):if s[right] in "aeiou":count += 1best = countfor right in range(k, len(s)):if s[right] in "aeiou":count += 1if s[right - k] in "aeiou":count -= 1best = max(best, count)return best
(nothing printed yet)Now write one that keeps a count and looks for the smallest.
A row of tiles is a string of "B" (black) and "W" (white). You can paint white tiles black. Write fewest_to_paint(tiles, k), which returns the fewest tiles you must paint so that some k tiles in a row are all black. k is between 1 and len(tiles).
For "BWWBWBB" and k = 3 the answer is 1: the window "BWB" (or "WBB") has one white tile. Slide a window: the notebook is the number of whites inside it. Then press Watch it run to see the count change.
raise NotImplementedError, then press Run tests. Each check says what it expects.Not every notebook slides. The largest item in the window looks as if it should slide like the count. Try it before reading on.
This code tries to keep largest, the largest item in each window of k = 3 items, by comparing it with each item that enters. It prints one line per window. What does the second line show, and is it right?
nums = [5, 1, 3, 2]
k = 3
largest = max(nums[:k])
print(largest)
for right in range(k, len(nums)):
largest = max(largest, nums[right])
print(largest)Choose one answer, then check.
A notebook can also be a whole Counter, a dict from each item to how many times it appears (module 3). Each slide adds 1 to the count of the item entering and subtracts 1 from the count of the item leaving. The module's practice bank has a medium of that kind, with letters: A rearrangement inside a string (LeetCode 567, Permutation in String).
Last, practice saying the plan. These are the sentences you will say before you type.
Explain, as you would to an interviewer before typing, how you would find the largest sum of any k items in a row. Name the brute force and its cost first. Then give the walk, the notebook, the promise and the cost of the slide, in a few plain sentences.
Saved in this browser as you type.