Reuse a Moving Region

Say you want the total of three consecutive readings, and then the total of the next three. Those two groups share two values! Once you’ve added up the first group, you can reuse that total by subtracting the value that leaves and adding the one that arrives.

A sliding window keeps track of one contiguous region as its boundaries move. For [4, 2, 7, 1], shifting a window of width three changes the total from 13 to 10:

Two rows of 4, 2, 7, and 1 highlight successive groups of three, labeled with totals 13 and 10.
One Value Out and One Value In

The middle values stay in the window, so you don’t need to add them again. Calling sum() on every slice repeats that work and creates temporary slices along the way. Updating a running total needs only a few operations per move.

Some windows have a fixed width. Others grow until a condition breaks, then shrink until it holds again. For a region with no repeated characters, adding one character may require several removals from the left. Before you decide how to move either boundary, describe the condition your current window satisfies.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.