Browse curriculum

Sliding Window

The sliding window technique processes subarrays efficiently by moving a window across the array instead of recomputing each subarray from scratch.

WINDOW 3

FIRST WINDOW

2

0

1

1

5

2

1

3

3

4

2

5

9

6

7

7

Window sum

8

Best so far

8

 

Sum the first 3 elements: 2 + 1 + 5 = 8. That is the only full sum this algorithm ever computes.

Next

Slide right: add 1, drop 2 → 7. Two operations, not 3. Best stays 8.

Array

Window

3

Intuition

Instead of re-calculating the sum of every subarray from scratch (O(n*k)), we can "slide" the window by one position: add the new element entering the window and subtract the element leaving it. This reduces the complexity to O(n).

Concept

  • Window: A range of elements [start, end].
  • Slide: Move start and end by 1.
  • Optimization: Reuse the result of the previous window.

How it Works

Algorithm:

  1. Calculate sum of first k elements.
  2. Set maxSum = currentSum.
  3. Loop from i = k to n-1:
  4. currentSum += arr[i] (Add new)
  5. currentSum -= arr[i-k] (Remove old)
  6. Update maxSum if needed.

Step-by-Step Breakdown

Watch the visualization:

  • Observe the window moving one step at a time.
  • See how the sum updates instantly by just +1 and -1 operation.

When to Use

  • Finding subarrays of fixed size K with specific properties (max sum, min avg).
  • Finding longest/shortest subarray with specific properties (dynamic window).
  • String problems (longest substring without repeating characters).

When NOT to Use

  • When the problem requires non-contiguous elements (subsequences).

How to Identify

"Subarray of size K", "Longest substring", "Consecutive elements".

Preparing for interviews? This topic is also taught as a pattern:

Introduction to Sliding Window

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is the difference between a fixed and a variable window?

A fixed window keeps length K, so each step adds one element on the right and drops one on the left. A variable window grows while a condition holds and shrinks from the left when it breaks, which is how longest and shortest subarray problems are solved.


Why is it faster than recomputing every subarray?

Because consecutive windows overlap. Recomputing each window is O(N*K), while updating the previous result with one addition and one subtraction makes each step O(1) and the whole scan O(N).


When does the technique not apply?

When the elements you need are not contiguous. Subsequence problems, where you may skip elements, are not window problems, and neither are cases where shrinking the window cannot restore the condition monotonically.