Command Palette

Search for a command to run...

← All patterns

Pattern · Pointers & Windows

Sliding Window: Fixed Size

Keep a window of exactly k elements; add the element entering and remove the one leaving instead of recomputing.

Time O(n) · Space O(1) or O(alphabet)

Taught in Module 7: Sliding Window

Think of it like this

A train window showing exactly three houses at a time: as the train moves, one house appears on the right and one disappears on the left.

Clues that point here

  • → "Subarray or substring of size k"
  • → Maximum or average of every k-length window
  • → Anagram or permutation of a fixed-length pattern inside a string

Not this pattern when

  • ✕ The window size depends on a condition (use a variable window)
  • ✕ Elements can be chosen out of order (subsequence, not subarray)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Sliding Window: Fixed Size · template
int windowSum = 0, best = Integer.MIN_VALUE;
for (int right = 0; right < arr.length; right++) {
    windowSum += arr[right];                 // element enters
    if (right >= k) windowSum -= arr[right - k];   // element leaves
    if (right >= k - 1) best = Math.max(best, windowSum);  // window is full
}
return best;

Common versions

  • Max sum of size k
  • Averages of subarrays of size k
  • Find all anagrams
  • Permutation in string

Practice problems with this pattern

Related patterns