Module 4 · Smart Patterns for Lists · Lesson 11 of 40
Sliding window
Keep a 'window' over part of a list and slide it, updating the answer instead of starting over.
In this lesson · about 22 minutes
- Solve fixed-size window problems in O(n)
- Grow and shrink a variable window
- Find the longest substring without repeating letters
Many problems ask about a run of items next to each other (a "subarray" or "substring"). For example: "What is the biggest sum of 3 numbers in a row?"
The slow way adds up every group of 3 from scratch. The sliding window way adds the first 3, then slides: take away the number that leaves on the left, add the number that joins on the right. Each slide costs 2 steps, so the whole thing is O(n).
Try it · see it work
Sliding window: biggest sum of k in a row
Watch the window slide. Notice that only two numbers change each time.
window sum
8
best
8
Step 1 of 8Add up the first 3 numbers: 2 + 1 + 5 = 8. Best so far: 8.
Variable-size windows
Sometimes the window size is not fixed. Then the window has a left and a right edge:
- Move
rightforward to grow the window, adding the new item. - If the window breaks a rule, move
leftforward to shrink it until the rule is OK again. - After each step, update the best answer.
Example: "the longest part of a word with no repeated letter". Grow to the right; if the new letter is already in the window, shrink from the left until it isn't. A set remembers which letters are in the window.
def longest_unique(s):
window = set()
left = best = 0
for right in range(len(s)):
while s[right] in window:
window.remove(s[left])
left += 1
window.add(s[right])
best = max(best, right - left + 1)
return best
Each letter enters the window once and leaves at most once, so this is O(n) even with the inner while.
Clues it's a sliding window problem
- "Subarray" or "substring" (items next to each other).
- "Longest", "shortest", "maximum sum of k", "at most k different".
Try it: longest part with no repeats
Exercise
Biggest sum of k in a row
Write max_window_sum(nums, k) that returns the largest sum of any k numbers next to each other. Add the first k numbers, then slide.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.