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

Lesson 4 of 4

Windows that grow and shrink

When the question asks for the longest or shortest block that obeys a rule, one window answers it in one pass. The right edge moves every step, and the left edge catches up only when the rule forces it.

About 2 hours 20 minutes, with the 4 problems worked in it
By the end you can
  • Explain why the left edge of a variable window never has to move back

  • Write the template for a longest answer (record after shrinking) and for a shortest answer (record before each shrink)

  • Choose the notebook a rule needs, such as a set, a running sum, letter counts or a missing counter

  • Explain why a while loop inside a for loop still costs O(n) here

  • Recognize when a window fails, such as sums with negative numbers

In the last lesson the window had a size you were given, such as the best total over 3 days in a row. Often the size is the answer itself. Two questions of that kind:

  • In the string "abcbde", how long is the longest stretch with no repeated character?
  • In daily sales [2, 1, 4, 3, 1, 5], what is the fewest days in a row whose sales add up to at least 8?

You could try every block. Six items have 21 blocks (6 of length 1, 5 of length 2, and so on down to 1 of length 6), and n items have about n2/2, so trying them all costs O(n2) or more. When n is 100,000, that is about 5 billion blocks.

This lesson answers both questions in one pass with a window that grows on the right and shrinks on the left. The same few lines then solve four classic problems, the last of them a hard one.

The longest stretch without a repeat

A substring is a block of consecutive characters: "cbd" is a substring of "abcbde", but "acd" is not. We want the longest substring with no character in it twice.

Brute force first: the direct method that tries every candidate. Start at each position, read to the right, and stop at the first repeat. Here is every walk on "abcbde":

StartReadsStops becauseLength
0a, b, c, bthe second b repeats3
1b, c, bthe second b repeats2
2c, b, d, ethe text ends4
3b, d, ethe text ends3
4d, ethe text ends2
5ethe text ends1

The best is 4, from start 2: "cbde". That took 17 reads for 6 characters, and most of the reads repeat earlier ones: the walk from start 1 reads b and c again and stops at the same b as the walk from start 0.

The walk from start 0 tells us more than its length. It stopped because positions 1 and 3 both hold b. Any walk that starts at 0 or 1 and reaches position 3 holds both b's, so it has to stop by position 2, and the best of those walks, "abc", is already counted. Starts 0 and 1 are finished. The next start worth trying is 2, right after the first b, and we already know that c and the second b fit together. Nothing needs to be read again.

As in the last lesson, a window is a block of consecutive positions from index left to index right, both included. In Python it is s[left:right + 1] (a slice stops before its end index, so we add 1), and its length is right - left + 1. What we did by hand is a variable window: a window whose size changes as it walks. The rule is what every window we keep must obey; here it is "no character twice". Move right one character at a time. When the new character is already inside, move left forward until the old copy is gone. left never moves back, because every start it passes is stuck behind a repeat.

The widget runs this on "abcbde". The cells are the characters and the bracket marks the window. The readouts show the characters inside it, kept in a set (module 3: a collection with no repeats, where asking "is this character inside?" takes one step on average), the best length so far, and how many times the pointers have moved. Before you press Next, guess how many times left moves.

Try the same moves by hand on a new string.

Work it outCount the left moves

Run the same moves by hand on "xyzzy": right reads one character per step, and when that character is already in the window, left moves forward until the old copy is gone. In all, how many times does left move? Type a whole number.

left moves

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

The template in code

How do the widget's moves look in Python? They fit in a few lines. The notebook, the values the walk keeps up to date, is a set named window that holds the characters of s[left:right + 1], plus left and best. enumerate(s) hands out each position with its character, so ch is always s[right]. Before you step through, guess what the function returns for "abba", and at which value of right the window has to shrink.

Step throughThe window template on "abba"
Step 1 of 30
Line 1 is about to run.
def longest_unique(s):
window = set()
left = 0
best = 0
for right, ch in enumerate(s):
while ch in window:
window.remove(s[left])
left += 1
window.add(ch)
best = max(best, right - left + 1)
return best
Names
no names yet
Output
(nothing printed yet)

Every pass makes the same three moves. This is the template for every problem in this lesson:

  1. Grow. right moves one step, and the new item is about to join the notebook.
  2. Shrink while the window breaks the rule. Drop s[left] from the notebook and move left forward. Here the rule is "no character twice", and the check comes before ch joins: a set cannot hold two copies, so the test is "would ch repeat?"
  3. Record. The window obeys the rule again, so its length is a candidate for best.

The three moves keep one promise, a fact that is true after every pass:

Why it holds: left passes a start only when the block from that start to right breaks the rule, and every longer block from the same start contains that block, so it breaks the rule too. So a start that left has passed can never begin a good window again. Every substring ends at some right, and we record the longest good one there, so when the walk ends best is the answer.

Check the promise on a new string: print the window after every pass.

PredictPrint every window

This is the template's loop with a print where the record line was, so it prints the window s[left:right + 1] after each pass. Type exactly what it prints, one window per line.

s = "aabcb"
window = set()
left = 0
for right, ch in enumerate(s):
    while ch in window:
        window.remove(s[left])
        left += 1
    window.add(ch)
    print(s[left:right + 1])

Two loops, still one pass

The while loop sits inside the for loop, and nested loops often mean O(n2). Here, count pointer moves instead of loop levels. right moves n times. left moves one step per pass of the inner loop, only forward, and it can never go past the end of the string, so over the whole walk it moves at most n times. Each move adds or removes one character from a set, O(1) on average. So the total is at most 2n moves: O(n) time. The widget counted 8 moves for 6 characters.

Here is the same template with a different rule, a budget, and a running sum as the notebook.

Put in orderMost days within a budget

Each day has a positive cost, and you have a budget. Put the lines in order to build longest_within(costs, budget), which returns the most days in a row whose total cost is at most budget (0 if no single day fits). Indentation is part of each line. Three lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • total += cost
    • total -= costs[left]
    • left += 1
    • best = max(best, total)
    • while total >= budget:
    • left, total, best = 0, 0, 0
    • def longest_within(costs, budget):
    • for right, cost in enumerate(costs):
    • return right - left + 1
    • while total > budget:
    • best = max(best, right - left + 1)
    • return best

    Now write the repeat-free window from a blank editor. The tests include "abba" and a string with no repeats at all.

    mediumSliding windowHash maps and sets target 25 min

    Longest stretch without a repeat

    A substring is a block of consecutive characters from a string: "ana" is a substring of "banana", but "bnn" is not.

    Return the length of the longest substring of s whose characters are all different. Every character counts, spaces included, and an upper case letter is a different character from its lower case form. An empty string has no characters, so its answer is 0.

    Example 1
    Inputs = "abcbde"Output4

    "cbde" has four different characters. Any longer block would hold both b's.

    Example 2
    Inputs = "banana"Output3

    "ban" works. Every block of 4 letters repeats an a or an n.

    Example 3
    Inputs = "zzzz"Output1

    Every block of 2 is "zz", so the best is a single z.

    Constraints
    • 0 ≤ len(s) ≤ 105

    • s can hold any characters: letters, digits, spaces and symbols.

    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.

    A dict works as the notebook too. Map each character to the last position where you saw it, and when ch has been seen before, left can jump past the old copy in one step:

    def longest_unique(s):
        last = {}                        # character -> the last position it was seen
        left = 0
        best = 0
        for right, ch in enumerate(s):
            if ch in last:
                left = max(left, last[ch] + 1)   # jump past the old copy, never back
            last[ch] = right
            best = max(best, right - left + 1)
        return best

    Keep the max. The dict never forgets, so it can point at a copy that is already outside the window. On "abba", when the last a arrives, left is 2 and the old a sits at 0. Without the max, left would jump back from 2 to 1 and count "bba", which repeats b, for a wrong answer of 3.

    Shortest instead of longest

    Back to the sales: [2, 1, 4, 3, 1, 5], and the fewest days in a row adding up to at least 8. Every number is positive, and that gives the window two clean moves: adding a day raises the sum, and dropping one lowers it.

    Turn the template around. Now we want the shortest window that reaches 8. Grow on the right until the sum reaches 8. That window is a candidate, so record its length first, then drop from the left to try a shorter one, and repeat while the sum is still at least 8. When the loop stops, the sum is below 8: that is the rule this window keeps after every inner loop. The only change from the longest version is where the recording happens.

    The widget shows the sum inside the bracket and the shortest length so far. Before you press Next, find the answer by eye: the fewest days in a row that add up to at least 8.

    In code, the record moves inside the while loop. The trace runs it on a shorter list, [1, 2, 6, 1] with target 7. Before you step through, guess how many times best changes after its first value.

    Step throughRecord, then shrink
    Step 1 of 32
    Line 1 is about to run.
    def shortest_subarray(nums, target):
    left = 0
    window_sum = 0
    best = len(nums) + 1
    for right, x in enumerate(nums):
    window_sum += x
    while window_sum >= target:
    best = min(best, right - left + 1)
    window_sum -= nums[left]
    left += 1
    return best if best <= len(nums) else 0
    Names
    no names yet
    Output
    (nothing printed yet)

    best = len(nums) + 1 means "none found yet", because no block is that long. The last line, return best if best <= len(nums) else 0, reads the way it sounds: return best if it is a real length, else 0.

    When the walk ends, the promise gives the answer. The last window is below the target, and every block that starts at left or later sits inside it, so with positive numbers none of those qualifies. Every start is covered.

    Quick checkA negative number sneaks in

    shortest_subarray from the trace above assumes positive numbers. What does it return for shortest_subarray([1, -2, 5], 4)?

    Choose one answer, then check.

    Here is the full problem. "At least" means >=.

    mediumSliding window target 25 min

    Shortest block that reaches a target

    Every number in the list nums is a whole number of at least 1, and so is target. A subarray is a block of consecutive items, such as [4, 1] in [3, 4, 1], and it holds at least one item.

    Find the shortest subarray whose items add up to target or more, and return its length. If even the whole list adds up to less than target, no subarray reaches it, so return 0.

    Example 1
    Inputnums = [3, 1, 4, 1, 5], target = 9Output3

    4 + 1 + 5 = 10 reaches 9. No single item does, and no two neighbors do: the biggest pair is 1 + 5 = 6.

    Example 2
    Inputnums = [1, 8, 2], target = 8Output1

    The single item 8 is already at least 8.

    Example 3
    Inputnums = [2, 2, 2], target = 7Output0

    Even the whole list sums to 6, so no subarray reaches 7.

    Constraints
    • 1 ≤ len(nums) ≤ 105

    • 1 ≤ nums[i] ≤ 104

    • 1 ≤ target ≤ 109

    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.

    A notebook of counts

    The next problem (LeetCode 424) gives you a string of capital letters and lets you change at most k of them. What is the longest block you can make all one letter?

    First, what one block needs. Take "AABA". The cheapest plan keeps the most common letter, A with 3 copies, and changes the rest: 1 letter. So a block needs its length minus the count of its most common letter in changes. With k = 1, "AABA" is good (4 − 3 = 1) and "AABAB" is not (5 − 3 = 2).

    That rule fits the template. The notebook is counts, a dict from each letter to its number of copies in the window; counts.get(ch, 0) reads a count, or 0 for a letter not seen yet. The shrink loop runs while the length minus max(counts.values()), the largest count, is above k. Before you step through, guess the answer for "AABAB" with k = 1.

    Step throughCounting letters in the window
    Step 1 of 34
    Line 1 is about to run.
    def longest_after_changes(s, k):
    counts = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
    counts[ch] = counts.get(ch, 0) + 1
    while (right - left + 1) - max(counts.values()) > k:
    counts[s[left]] -= 1
    left += 1
    best = max(best, right - left + 1)
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Why recompute the maximum instead of keeping it in one variable? When a letter leaves, the top count can drop, or another letter can take the lead, as B did here. max(counts.values()) looks at no more than 26 counts, a fixed cost, so the walk stays O(n).

    Practice counts with a different rule first: at most two different characters.

    Code itAt most two kinds

    Write longest_two_kinds(s), which returns the length of the longest substring of s that uses at most two different characters. Use the template with a dict of counts: counts[c] is how many times c appears in the window. Then press Watch it run to see the dict grow and shrink.

    ⌘+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.

    Now the changes problem itself.

    mediumSliding windowHash maps and sets target 25 min

    Longest run after a few changes

    A string s holds uppercase letters. You may change at most k of its letters, each into any uppercase letter. You do not have to use all k changes.

    Return the length of the longest block of consecutive positions that can be made all the same letter. The changes are imagined: return the length and leave s as it is.

    Example 1
    Inputs = "ABBA", k = 1Output3

    Change the first A to B: "BBBA" starts with three B's. A block of four would need two changes.

    Example 2
    Inputs = "CCDCCD", k = 1Output5

    Change the first D to C: "CCCCCD" starts with five C's. All six letters would need both D's changed.

    Example 3
    Inputs = "XYZ", k = 0Output1

    With no changes allowed, the longest block of one letter has length 1.

    Constraints
    • 1 ≤ len(s) ≤ 105

    • s holds only uppercase letters A to Z.

    • 0 ≤ k ≤ len(s)

    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.

    Covering a set of letters

    The capstone, LeetCode 76, is a hard problem. A substring of text covers letters if it holds every character of letters at least as many times as letters does. To cover "AAB" it needs two A's and one B, and other characters may sit inside too. We want the shortest substring that covers.

    Covering behaves like a sum of positive numbers: adding a character never breaks a cover, and dropping one never creates a cover. So this is the shortest version of the template: grow until the window covers, then record and shrink while it still covers.

    The hard part is the notebook. LeetCode's strings hold upper and lower case letters, 52 kinds, so comparing every count at every step means up to 52 checks each time, and more code to get right. Two names do the job:

    • need[c]: how many more copies of c the window needs. It starts as the count of c in letters and goes below 0 when the window holds extras.
    • missing: how many characters are still needed, counting repeats. The window covers exactly when missing is 0.

    When ch enters, if need[ch] was above 0, this copy fills a real gap, so missing drops by 1; either way need[ch] drops by 1. When text[left] leaves, its need rises by 1, and if that makes it above 0, a needed copy has gone, so missing rises by 1.

    Counter(letters) (module 3) counts each character of letters, and a Counter answers 0 for a key it does not hold, so need["B"] is 0 even though letters has no B. Before you step through, guess the answer for "BAAC" with letters "AC".

    Step throughNeed and missing
    Step 1 of 51
    Line 1 is about to run.
    from collections import Counter
    def min_window(text, letters):
    need = Counter(letters)
    missing = len(letters)
    left = 0
    best_start, best_len = 0, len(text) + 1
    for right, ch in enumerate(text):
    if need[ch] > 0:
    missing -= 1
    need[ch] -= 1
    while missing == 0:
    if right - left + 1 < best_len:
    best_start, best_len = left, right - left + 1
    leaving = text[left]
    need[leaving] += 1
    if need[leaving] > 0:
    missing += 1
    left += 1
    if best_len > len(text):
    return ""
    return text[best_start:best_start + best_len]
    Names
    no names yet
    Output
    (nothing printed yet)

    Work one by hand before the full problem.

    On paperNeed and missing by hand

    Find the shortest substring of "ADBA" that covers "AB", by hand. On paper, track need, missing and left as each character enters, the way the trace did. Reveal one step at a time and check yourself.

    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.

    length of the shortest cover

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    This is the only hard problem in the module, with a target time of 40 minutes. If you are still stuck after about 30 minutes of real effort, read the approach, then re-solve it from a blank editor on another day.

    hardSliding windowHash maps and sets target 40 min

    Smallest window that covers a set of letters

    You get two strings, text and letters. A substring of text (a block of consecutive characters) covers letters if it holds every character of letters at least as many times as letters does. To cover "AAB", a substring needs two A's and one B, and it may hold other characters too.

    Return the shortest substring of text that covers letters. If several shortest ones exist, return the one that starts first. If none exists, return the empty string "".

    Example 1
    Inputtext = "AXBYCAB", letters = "ABC"Output"CAB"

    "AXBYC" covers A, B and C, but the shorter "CAB" at the end covers them too. Three letters need at least three characters, so nothing is shorter.

    Example 2
    Inputtext = "BAAXB", letters = "AAB"Output"BAA"

    Repeats count: the window needs two A's. "BAA" has them, and so does "AAXB", which is longer.

    Example 3
    Inputtext = "A", letters = "AA"Output""

    The text has only one A, so nothing covers two.

    Constraints
    • 1 ≤ len(text) ≤ 105

    • 1 ≤ len(letters) ≤ 105

    • Both strings hold upper and lower case English letters. Case matters: "a" does not cover "A".

    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.

    Four problems, one template. They differ in the rule, the notebook and where the record happens:

    ProblemRule the window keepsNotebookWhen to record
    Longest without a repeatno character twicea setafter the shrink loop
    Longest after k changeslength minus top count is at most kletter countsafter the shrink loop
    Shortest reaching a targetsum below the targeta running suminside the loop, before each shrink
    Shortest covering lettersdoes not cover yetneed and missinginside the loop, before each shrink

    A window fits when the answer is one block and growing it can only break the rule, so shrinking is the one repair. Try that test on four new questions.

    Quick checkDoes a window fit?

    Which of these can a variable window answer in one pass? Choose every one that fits.

    Choose every option that applies, then check.

    Last, say it the way you would in the room.

    Say itSay it like you would in the room

    An interviewer asks for the most days in a row whose total cost stays at most a budget (every cost is positive). Before typing, say the walk, the notebook, the promise and the cost. Then answer the follow-up: "Your while loop is inside a for loop. Isn't that O(n2)?"

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint