The sliding window pattern, with templates

The sliding window pattern solves problems about contiguous stretches of an array or string by moving two indexes forward instead of checking every stretch. The right index adds one element at a time, the left index drops elements when the window breaks a rule (or, for shortest-window questions, while it still satisfies it), and a small running summary such as a sum or a count table is updated in O(1). That turns O(n^2) or worse into O(n), provided the rule only gets harder to satisfy as the window grows.

By Published 9 min read

What the pattern is

A window is a stretch of consecutive positions, from index left to index right. The brute force for any window question is to try every pair of ends, which is O(n^2) windows and often O(n) work to evaluate each one. The sliding window saves two things at once. Each end only moves forward, so there are at most 2n moves in total. And the window's summary (its sum, its character counts, its number of distinct values) is updated as elements enter and leave rather than recomputed from scratch.

The idea only works when moving forward is always safe. If a window breaks the rule, every larger window with the same left end also breaks it; if a window satisfies the rule, every window inside it does too (or the reverse, for shortest-window questions). That property, called monotone validity, is what you should state out loud in an interview before writing the loop.

How to spot a sliding window problem

Clues in a prompt and the window shape they suggest
Clue in the promptWindow shapeRunning summary
"every block of k consecutive", "average over each k days"Fixed size kSum, or a deque for maximum
"longest substring with at most / without ..."Variable, longest validCount table or last-seen index
"smallest subarray whose sum reaches ...", "shortest stretch containing ..."Variable, shortest validSum, or counts of what is still missing
"how many subarrays have exactly k ..."Two variable windows (at most k minus at most k - 1)Count table
Numbers can be negative, or the rule is about balance or orderProbably not a windowPrefix sums, a stack or DP instead
Clues in a prompt and the window shape they suggest. Scroll sideways on a small screen.

The three shapes, with a small example each

  • Fixed size. For the numbers 4, -1, 6, 2, -5, 3 and windows of three, the sums are 9, 7, 3 and 0. Each new sum is the previous one plus the entering number minus the leaving number, so the best, 9, takes one pass.
  • Longest valid. In the string aabcbcdbca, the longest stretch using at most two different letters has length 4 (bcbc). When a third letter enters, the left end moves until only two remain.
  • Shortest valid. For the positive numbers 1, 4, 1, 1, 3, 2 and a target of 6, the shortest stretch summing to at least 6 has length 3 (1, 3, 2). Once the window reaches 6, it shrinks from the left as long as it stays at 6 or more.
  • Count exactly k. For 3, 1, 3, 2, 2 there are 5 subarrays with exactly two distinct values. Counting subarrays with at most k is a window problem; exactly k is the difference of two such counts.

Templates in Python

def max_sum_fixed(nums, k):
    """Largest sum of any k consecutive numbers (fixed-size window)."""
    if k <= 0 or k > len(nums):
        raise ValueError("k must be between 1 and len(nums)")
    window = sum(nums[:k])
    best = window
    for right in range(k, len(nums)):
        window += nums[right] - nums[right - k]  # one in, one out
        best = max(best, window)
    return best


def longest_at_most_k_distinct(s, k):
    """Longest stretch of s with at most k different characters."""
    counts = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
        counts[ch] = counts.get(ch, 0) + 1
        while len(counts) > k:          # window broke the rule: shrink
            out = s[left]
            counts[out] -= 1
            if counts[out] == 0:
                del counts[out]
            left += 1
        best = max(best, right - left + 1)  # window is valid here
    return best


def shortest_sum_at_least(nums, target):
    """Shortest stretch of positive numbers whose sum is >= target, or 0."""
    left = 0
    total = 0
    best = float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:          # window is valid: record, then shrink
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else best


def count_exactly_k_distinct(nums, k):
    """Number of subarrays with exactly k distinct values."""
    def at_most(m):
        if m < 0:
            return 0
        counts = {}
        left = 0
        total = 0
        for right, x in enumerate(nums):
            counts[x] = counts.get(x, 0) + 1
            while len(counts) > m:
                counts[nums[left]] -= 1
                if counts[nums[left]] == 0:
                    del counts[nums[left]]
                left += 1
            total += right - left + 1   # every window ending at right
        return total
    return at_most(k) - at_most(k - 1)
All four shapes. Run against random inputs and a brute force over every subarray.

Look at where the answer is recorded in each version. In the longest-valid loop, it is recorded after the inner while, because that is when the window is valid again. In the shortest-valid loop, it is recorded inside the while, because every pass of that loop is a valid window that is about to get shorter. Swapping those two places is the most common bug in window code.

Templates in JavaScript

function maxSumFixed(nums, k) {
  if (k <= 0 || k > nums.length) throw new RangeError("k must be between 1 and nums.length");
  let windowSum = 0;
  for (let i = 0; i < k; i++) windowSum += nums[i];
  let best = windowSum;
  for (let right = k; right < nums.length; right++) {
    windowSum += nums[right] - nums[right - k];
    best = Math.max(best, windowSum);
  }
  return best;
}

function longestAtMostKDistinct(s, k) {
  const counts = new Map();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    counts.set(s[right], (counts.get(s[right]) ?? 0) + 1);
    while (counts.size > k) {
      const out = s[left];
      counts.set(out, counts.get(out) - 1);
      if (counts.get(out) === 0) counts.delete(out);
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

function shortestSumAtLeast(nums, target) {
  let left = 0, total = 0, best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    total += nums[right];
    while (total >= target) {
      best = Math.min(best, right - left + 1);
      total -= nums[left];
      left++;
    }
  }
  return best === Infinity ? 0 : best;
}

function countExactlyKDistinct(nums, k) {
  const atMost = (m) => {
    if (m < 0) return 0;
    const counts = new Map();
    let left = 0, total = 0;
    for (let right = 0; right < nums.length; right++) {
      counts.set(nums[right], (counts.get(nums[right]) ?? 0) + 1);
      while (counts.size > m) {
        const out = nums[left];
        counts.set(out, counts.get(out) - 1);
        if (counts.get(out) === 0) counts.delete(out);
        left++;
      }
      total += right - left + 1;
    }
    return total;
  };
  return atMost(k) - atMost(k - 1);
}
The same four functions. A Map keeps counts; its size is the number of distinct values.

The at-most trick for exactly k

"Exactly k distinct" is not monotone: a window with too few distinct values may become valid by growing, and one with too many becomes valid by shrinking. "At most k distinct" is monotone, and for each right end, every window from the current left up to right is valid, which is right - left + 1 windows. So count at most k, count at most k - 1, and subtract. The same move works for "exactly k odd numbers" or "sum exactly s" over non-negative numbers.

Cost

Time and memory of the templates, n = input length, d = distinct values in a window
TemplateTimeExtra memory
Fixed size, sumO(n)O(1)
Longest valid with a count tableO(n)O(d)
Shortest valid with a running sumO(n)O(1)
Exactly k via two at-most passesO(n)O(d)
Brute force over every subarrayO(n^2) windows, often O(n^3) totalO(1) to O(d)
Time and memory of the templates, n = input length, d = distinct values in a window. Scroll sideways on a small screen.

The inner while does not make these O(n^2). Every pass of it moves left forward by one, and left never moves past right, so across the whole run the inner loop executes at most n times. Saying this sentence is how you defend the complexity when an interviewer points at the nested loop.

When a window does not work

  • Negative numbers with a sum target. Adding an element can lower the sum, so shrinking is no longer safe. Use prefix sums with a hash map instead.
  • Balance or order rules. A substring of brackets can be invalid, then valid again as it grows. Longest Valid Parentheses looks like a window question and needs a stack.
  • Non-contiguous picks. "Choose any elements" is a subsequence question, usually DP or greedy.
  • The best window depends on the whole window at once, such as a median. A window still applies, but the summary needs two heaps or a sorted structure, and the cost rises to O(n log n).

Problems to practice the pattern

  • Longest Substring Without Repeating Characters: longest valid, where the summary is the last index each character was seen.
  • Minimum Window Substring: shortest valid, with a count of characters still missing.
  • Sliding Window Maximum: fixed size, where the summary is a deque instead of a sum.
  • Longest Valid Parentheses: the useful counterexample, a contiguous-substring question where shrinking is not safe.
  • Longest run of ones if you may flip up to k zeros. Longest valid; the summary is the count of zeros in the window.
  • Maximum average of any k consecutive values. Fixed size; divide the best sum by k at the end.

Mistakes that cost points

  • Recording the answer in the wrong place (see the note under the Python templates).
  • Using if instead of while for the shrink step, which leaves the window invalid when more than one element must leave.
  • Forgetting to delete a key whose count drops to zero, so the number of distinct values never goes down.
  • Applying the shortest-valid template to numbers that can be negative.
  • Off-by-one window length: it is right - left + 1 when both ends are included.
  • Not stating why the left end never needs to move back. Without that, the O(n) claim is a guess.

How to explain it out loud

Fictional example

Talking through a longest-valid window
Candidate
The question is about a contiguous substring and asks for the longest one, so I am thinking sliding window. Before I commit: if a window has more than two distinct letters, any bigger window with the same start does too. So once it breaks, moving the left end forward is safe.
Candidate
I will keep a count per letter. The right end adds a letter; while there are more than two keys, I remove from the left. After that loop the window is valid, so I compare its length to the best.
Interviewer
There is a loop inside a loop. Is that quadratic?
Candidate
No. The left index only moves forward and never passes the right one, so the inner loop runs at most n times in total. Overall it is O(n), with memory for the counts.

Practicing window problems with Natively

Most window bugs are about where one line sits, which is hard to see in your own code and easy to hear when you explain it. In practice sessions, Natively transcribes your explanation on your Mac or Windows computer, so you can reread whether you stated monotone validity before coding. You can also take a screenshot of a practice prompt and ask it which window shape fits and why, then compare its reasoning with yours. More on these features is on the page about the AI assistant for coding interviews.

Questions people ask

What is the sliding window technique?

A way to solve questions about contiguous subarrays or substrings by moving a left and a right index forward only, updating a running summary such as a sum or a count table as elements enter and leave, so the whole pass is O(n).

How do I know when to use a sliding window?

When the question is about a contiguous stretch (longest, shortest, best or count) and validity is monotone: once a window breaks the rule, growing it further from the same start cannot fix it.

Why is a sliding window O(n) with a nested loop?

The inner loop only moves the left index forward and it never passes the right index, so across the whole run it executes at most n times.

When does the sliding window not work?

When numbers can be negative in a sum question, when validity depends on balance or order such as brackets, or when the elements chosen need not be contiguous.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP