Fixed-Size vs Variable-Size Sliding Window
Fast recall
Quick revision
Core answer
Conceptual clarity on the two variants and the ability to recognize which applies from the problem's constraints
Applying a fixed-size template to a variable-size problem, forcing a size when it should be dynamic
Give a concrete example for each and state the rule: a number for size -> fixed; a condition like at most K distinct -> variable
Interview-ready guide
Interview answer
The difference between fixed-size and variable-size sliding window is whether the window has a constant size or changes dynamically.
In a fixed-size window, the problem tells you the exact size k, like find the maximum sum of any five consecutive elements. You compute the first window of five elements, then slide it across the array by removing the leftmost element and adding the next element on the right. The window always has exactly five elements.
The loop structure is simple, one for loop starting at index k, and in each iteration you do windowSum equals windowSum minus arr at i minus k plus arr at i. It's O of n time. In a variable-size window, the problem gives you a condition, not a size.
For example, find the longest substring with at most two distinct characters. You don't know the answer length in advance. You use two pointers, left and right.
The right pointer expands to add elements to the window. When the condition breaks, like you now have three distinct characters, you shrink from the left until the condition is valid again. The window size changes throughout the process.
The loop structure is a for loop that moves right, and inside it there's a while loop that moves left when needed. It's still O of n because each element is processed at most twice. A fixed-size update cannot solve a variable-size condition unless the valid window length is known in advance.
If you see the words longest or shortest with a condition, or at most K, that's variable-size. If you see size k or exactly k elements, that's fixed-size.
Fixed-Size vs Variable-Size Sliding Window
Direct Answer
A fixed-size window keeps a constant size K, always removing the leftmost element before adding a new right one. A variable-size window expands the right pointer until a condition breaks, then shrinks from the left until valid again. Fixed-size uses one loop; variable-size uses two pointers with expand/contract logic.
Common Mistakes & Pitfalls
Applying a fixed-size template to a variable-size problem, forcing a size when it should be dynamic
Check your understanding
Answer these without looking back at the article.
- Can a fixed-size window problem always be solved with a variable-size approach?
- How do you decide the initial window setup before the main loop?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.