Python 3D Academyবাংলা

Sliding Window in Python

Chapter 37: Sliding Window

4 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. A window of fixed size: moving sums and averages

    Keep a running total of the k items in the window, and when the window slides one place, add the item that comes in and subtract the one that goes out.

  2. A window that grows and shrinks: the longest stretch without repeats

    A window [l, r) whose size changes: grow it on the right one item at a time, and whenever the rule breaks, shrink it from the left until the rule holds again.

  3. Windows with counts: the shortest window with everything you need

    Grow the window until it covers every needed letter (with enough copies), then shrink it from the left while it still covers them, remembering the shortest covering window.

  4. When does a sliding window work?

    A grow-and-shrink window finds the answer whenever the rule is monotone: if a window breaks the rule, every bigger window around it breaks it too, and if a window keeps it, every smaller window inside it keeps it too.