Sliding Window

Find the biggest sum of 3 numbers in a row by sliding a window along: add the new number, drop the old one.

Python · intermediate · 6 min · 16 steps · free

What you'll learn

sliding_window.py

def max_window_sum(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

print(max_window_sum([2, 1, 5, 1, 3, 2], 3))

Step by step

  1. Python defines the function max_window_sum(). Its body does not run yet: it runs each time the function is called.
  2. Python calls max_window_sum(), with nums = [2, 1, 5, 1, 3, 2] and k = 3. It gets its own names.
  3. The first window is the first 3 numbers: 2 + 1 + 5 = 8.
  4. best is created with the value 8.
  5. i is created with the value 3.
  6. Slide right: add nums[3] (1) and drop nums[0] (2). The window is now 1 + 5 + 1 = 7, without adding all three again.
  7. Line runs: best = max(best, window).
  8. i changes from 3 to 4.
  9. window changes from 7 to 9.
  10. 5 + 1 + 3 = 9 beats 8: the best so far.
  11. i changes from 4 to 5.
  12. window changes from 9 to 6.
  13. Line runs: best = max(best, window).
  14. Python moves to the next item of the loop: for i in range(k, len(nums)).
  15. The function returns best.
  16. max_window_sum() has finished, so its names are gone. It prints 9.

Common mistakes

Best practices

Key takeaways

Check yourself

Updating the window costs?

Answer: O(1)

Good fit for "longest substring without repeats"?

Answer: Yes

·

More in Complexity and Searching