DSA · Patterns, not puzzles

How does the sliding window technique work?

Mediumsliding-windowsubstringsarraysUpdated Oct 2026
Quiz this track

Short answer

A sliding window maintains a contiguous range and updates its state as the boundaries move. It turns problems about the best or valid subarray into O(n) work when each element enters and leaves the window once.

The window is defined by a left and right boundary. The right boundary expands the window, and the left boundary contracts it when the window becomes invalid. You maintain summary state, such as a sum or a frequency map, instead of recomputing from scratch.

js
function longestUnique(text) {
  const lastSeen = new Map();
  let left = 0;
  let best = 0;
  for (let right = 0; right < text.length; right++) {
    const ch = text[right];
    if (lastSeen.has(ch) && lastSeen.get(ch) >= left) {
      left = lastSeen.get(ch) + 1;
    }
    lastSeen.set(ch, right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}
The left boundary jumps past the previous occurrence, so every character is processed a constant number of times.

Two window shapes

  • Fixed-size window: add the new element and remove the element that leaves
  • Variable-size window: expand until invalid, then shrink until valid again
  • Maintain a count, sum or frequency map instead of rescanning the window
  • Be careful when the validity condition can change in both directions

The complexity argument is important. Even though there is an inner while loop, each element is added at most once and removed at most once, so the total work is O(n). Say that explicitly rather than claiming the inner loop makes it O(n^2).

Sliding window requires contiguity. If the problem asks for a subsequence or an arbitrary subset, a window is usually the wrong tool.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is the variable-size window O(n) despite the inner loop?
  2. 2How would you find the smallest subarray with sum at least k?
  3. 3When does a sliding window not apply?
  4. 4How do you handle negative numbers in a sum window?

Say it in the interview

A sliding window keeps a contiguous range and maintains summary state as the boundaries move. The right edge expands and the left edge shrinks when the window breaks the condition. Each element enters and leaves once, so the total work is linear even with an inner loop. I use it for longest or shortest subarray and substring problems, and I avoid it for subsequences because those are not contiguous.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.