Fixed-size vs variable-size windows

Sliding window Junior Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Which question needs a variable window rather than a fixed one?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Longest run of days whose spending stays within a budget

Right: the window size is the answer, so it must grow and shrink.

When the window's length is what you are solving for, it has to change as you scan.

Why not the others?
  • B Highest total over any 7 consecutive days. The size is given, so a fixed window fits.
  • C Every 3-letter stretch that rearranges to 'abc'. The size is the pattern length, so it is fixed.

30-second answer

A fixed window has a size given by the question (k items); each step adds one item and removes one. A variable window grows on the right and shrinks on the left until a rule holds again, and the answer is a longest or shortest valid window. Both are O(n) because each item enters and leaves once.

Practise saying it · 45 s. No recording, just a timer

Compare fixed and variable windows.

Say your answer out loud, then check which of these points you covered:

  • Fixed: add one, remove one
  • Variable: grow and shrink
  • Monotonic rule needed

Deep dive

Fixed: 'every k consecutive', 'average of k', 'rearranged pattern of length m'.

Variable: 'longest with at most', 'shortest with at least', 'no repeats'.

The variable window needs a monotonic rule: if a window breaks it, every bigger window containing it breaks it too.

Common mistakes

  • Using a variable window when the rule is not monotonic (for example sums with negative numbers).
  • Re-summing each fixed window, which is O(n·k).

Senior take & follow-ups

Name the monotonic rule out loud. It is the condition that makes shrinking correct.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do rate limiters use windows?

    Show hint

    Fixed-window counters reset per period; sliding-window logs or counters smooth the edges between periods.

  2. What changes for 'exactly k'?

    Show hint

    Often 'at most k' minus 'at most k - 1'.

Similar on Backend: Rate limiting with a token bucket Rate limiters reuse the same two shapes: a fixed window counts requests per period, a sliding window counts the last N seconds. Here the window runs over an array instead of a clock.

What each operation costs: Arrays · Deque

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.