DSA Pattern: Sliding Window

Learn fixed and variable sliding windows for subarray and substring problems.

Back to Learn DSA

Sliding window is a pattern for problems about continuous ranges inside an array or string.

Instead of recomputing a range again and again, the window moves one step at a time while reusing previous work.

Fixed-size window

Use this when the problem gives a size k.

Example: maximum sum of any subarray of length k.

function maxSumOfK(values, k) {
	let windowSum = 0;

	for (let i = 0; i < k; i++) {
		windowSum += values[i];
	}

	let best = windowSum;

	for (let right = k; right < values.length; right++) {
		windowSum += values[right];
		windowSum -= values[right - k];
		best = Math.max(best, windowSum);
	}

	return best;
}

Variable-size window

Use this when the window expands and shrinks based on a condition.

Common examples include longest substring without repeating characters and smallest subarray with sum at least target.

Complexity

Most sliding window solutions are O(n) because each pointer moves forward at most n times.

Common signs

Practice problems

  1. Maximum sum of a subarray of size k.
  2. Average of every subarray of size k.
  3. Longest substring without repeating characters.
  4. Smallest subarray with sum at least target.
  5. Longest subarray with at most two distinct values.

Interactive walkthrough

Sliding Window Visualizer

Move a continuous range without recomputing everything.
Step 1 left
Step 2 sum
Step 3 right
Step 4 best