iq.lab
Python starts when a code cell comes near or you run one
04 Two pointers and sliding windows

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).

About 1 hour 10 minutes, with the problem worked in it
By the end you can
  • 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 - k and the window's first position with right - k + 1

  • Explain 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?

Step throughAdding up every window from scratch
Step 1 of 46
Line 1 is about to run.
def max_window_sum_slow(nums, k):
best = float("-inf")
for start in range(len(nums) - k + 1):
total = 0
for i in range(start, start + k):
total += nums[i]
best = max(best, total)
return best
Names
no names yet
Output
(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.

Work it outAdditions from scratch

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.

additions

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?

Step throughSliding the window
Step 1 of 30
Line 1 is about to run.
def max_window_sum(nums, k):
window_sum = 0
for right in range(k):
window_sum += nums[right]
best = window_sum
left = 0
for right in range(k, len(nums)):
window_sum += nums[right]
window_sum -= nums[left]
left += 1
best = max(best, window_sum)
return best
Names
no names yet
Output
(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.

PredictSlide and print

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.

rightentersleaveswindow after the slidewindow_sum
first windownonenonepositions 0 to 2: [2, 1, 5]8
312, at position 0positions 1 to 3: [1, 5, 1]7
431, at position 1positions 2 to 4: [5, 1, 3]9
525, at position 2positions 3 to 5: [1, 3, 2]6

Read down the columns and three rules appear:

  • The item leaving sits at right - k. When right is 3 it is at 0, and when right is 5 it is at 2. In the trace, left held exactly that value each time we subtracted.
  • The window that ends at right starts at right - k + 1. It holds positions right - k + 1 through right, which is k items.
  • right runs from k to n − 1, which is range(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.

Quick checkWhich item leaves?

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 in orderThe short version

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • window_sum = sum(nums[right - k + 1:right + 1])
    • def max_window_sum(nums, k):
    • return best
    • window_sum = sum(nums[:k])
    • for right in range(k, len(nums)):
    • best = window_sum
    • best = 0
    • best = 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 paperTrace it by hand

    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 best

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    the returned value

    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:

    nkadd every window: (n − k + 1) × kslide: k + 2 × (n − k)
    63129
    1,00010090,1001,900
    100,00050,0002,500,050,000150,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.

    Quick checkWhat the slide costs

    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).

    easySliding window target 15 min

    Largest average window

    You get a list of integers nums and a whole number k. A window is a block of k items that sit next to each other: positions i through i + k - 1. Of all the windows in nums, find the one whose items have the largest average, and return that average as a float.

    A float can carry a tiny rounding error, so the tests pass any result within 0.00001 of the exact average.

    Example 1
    Inputnums = [4, 2, 8, 1, 6], k = 2Output5.0

    The windows are [4, 2], [2, 8], [8, 1] and [1, 6]. [2, 8] has the largest sum, 10, so its average is 10 / 2 = 5.0.

    Example 2
    Inputnums = [-3, -1, -4, -2], k = 3Output-2.33333 (that is, -7 / 3)

    The windows sum to -8 and -7. The larger is -7, and -7 / 3 is about -2.33333.

    Example 3
    Inputnums = [1, 2], k = 2Output1.5

    The only window is the whole list. Its average is 1.5, a float, even though every item is an integer.

    Constraints
    • 1 ≤ k ≤ len(nums) ≤ 105

    • -104 ≤ nums[i] ≤ 104

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Step throughCounting vowels in a sliding window
    Step 1 of 30
    Line 1 is about to run.
    def most_vowels(s, k):
    count = 0
    for right in range(k):
    if s[right] in "aeiou":
    count += 1
    best = count
    for right in range(k, len(s)):
    if s[right] in "aeiou":
    count += 1
    if s[right - k] in "aeiou":
    count -= 1
    best = max(best, count)
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Now write one that keeps a count and looks for the smallest.

    Code itFewest tiles to paint

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says 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.

    Quick checkA maximum that tries to slide

    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.

    Say itSay it like you would in the room

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Windows that grow and shrink