← Learning Hub
Intermediate

Sliding Window and Prefix Sums

For questions about contiguous parts of an array or string ("subarray", "substring"), keep a window and slide it, instead of recomputing from scratch.

Many problems ask about a continuous part of an array or string: the best 3-day sales, the longest substring without repeats. Instead of re-checking every possible window (slow), a sliding window moves its edges forward, adding and removing one item at a time - turning O(n²) into O(n).

Fixed-size window

Example
You can edit this code.

Variable-size window

Longest substring without repeating characters - grow the right side, shrink the left side when a letter repeats.

Example
You can edit this code.

Prefix sums

Store running totals once; then any range sum is a single subtraction - O(1) per question.

Example
You can edit this code.
Hint words in questions: "subarray", "substring", "consecutive", "window of size k" usually mean sliding window or prefix sums.
Key points
  • A window is a continuous range; slide it instead of recalculating.
  • Fixed-size and variable-size windows are the two kinds.
  • Two pointers on sorted data is a close cousin.

📝 Test yourself

1. What is the time complexity of a sliding window over n items?
2. With prefix sums, a range sum costs...
3. Fill in the itertools function that makes running totals:
list((sales))