Fixed-Size vs Variable-Size Sliding Window (Interview Con...

Interview Concept: Fixed-Size vs Variable-Size Sliding Window

  • Fixed-size window: the window length k is given upfront and never changes; slide it by adding the new element on the right and removing the oldest on the left, one step at a time. Used for: max/average/first-negative in every window of size k.
  • Variable-size window: the window grows or shrinks based on a condition (sum, distinct count, character frequency). The right pointer always advances; the left pointer advances only when the condition is violated. Used for: minimum size subarray sum, longest substring with at most k distinct characters.
  • Shared trait: both styles keep the total pointer movement at O(n), since the left pointer, even in the variable case, never moves backward.
  • How to tell them apart in a problem statement: a fixed window has a stated constant length ("subarray of size k"); a variable window has a constraint to satisfy ("smallest/largest subarray such that...").

Complexity

Both styles run in O(n) time and O(1) to O(k) space, depending on whether extra frequency tracking is needed, because in both cases the left and right pointers each traverse the array at most once.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.