Skip to the content

Lesson 126 of 296

Sliding window: variable size

What you will learn

  • Windows that grow and shrink
  • The expand-right, shrink-left template
  • Best Time to Buy and Sell Stock
  • Longest Substring Without Repeating Characters
  • Longest Repeating Character Replacement
  • Minimum Window Substring
On this page

The idea

In many problems the window size is not fixed. You want the longest or shortest window that meets a condition. Template:

  1. Move right forward to expand the window, adding the new item.
  2. While the window is invalid (or, for "shortest", while it is still valid), move left forward to shrink it, removing items.
  3. Update the answer.

Each item enters the window once and leaves at most once, so the total work is O(n), even though there is a loop inside a loop.

Best Time to Buy and Sell Stock

Problem (LeetCode 121): prices[i] is the price on day i. Buy once and sell once later. Return the maximum profit (0 if none).
[7, 1, 5, 3, 6, 4] → 5 (buy at 1, sell at 6).

Idea: walk through the days, remembering the lowest price so far (the best day to have bought). At each day, check the profit if you sold today.

TypeScript
function maxProfit(prices: number[]): number {
  let minPrice = Infinity;
  let best = 0;
  for (const price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else {
      best = Math.max(best, price - minPrice);
    }
  }
  return best;
}

O(n) time, O(1) space. Thinking of it as a window: left is the buy day; whenever a lower price appears, the window restarts there.

Longest Substring Without Repeating Characters

Problem (LeetCode 3): length of the longest substring with all different characters.
"abcabcbb" → 3 ("abc"). "pwwkew" → 3 ("wke").

Idea: grow the window to the right. If the new character is already inside the window, move left until it is not. Store each character's last index in a Map so left can jump straight past the repeat.

TypeScript
function lengthOfLongestSubstring(s: string): number {
  const lastIndex = new Map<string, number>();
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right]!;
    const previous = lastIndex.get(ch);
    if (previous !== undefined && previous >= left) {
      left = previous + 1;
    }
    lastIndex.set(ch, right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}

previous >= left matters: a character seen before the current window does not count as a repeat.

Trace "abba":

rightchleft afterwindowbest
0a0"a"1
1b0"ab"2
2b2"b"2
3a2 (old "a" at 0 is outside)"ba"2

O(n) time, O(k) space for k different characters.

Longest Repeating Character Replacement

Problem (LeetCode 424): you may change up to k characters. Return the length of the longest substring that can be made of one repeated letter.
s = "AABABBA", k = 1 → 4.

Idea: a window is valid if windowLength - countOfMostCommonLetter <= k (the other letters are the ones you would replace).

TypeScript
function characterReplacement(s: string, k: number): number {
  const counts = new Map<string, number>();
  let left = 0;
  let maxCount = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right]!;
    const count = (counts.get(ch) ?? 0) + 1;
    counts.set(ch, count);
    maxCount = Math.max(maxCount, count);
    while (right - left + 1 - maxCount > k) {
      const leftCh = s[left]!;
      counts.set(leftCh, counts.get(leftCh)! - 1);
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Note: maxCount is not decreased when shrinking. That is safe: the answer can only improve when a new, higher maxCount appears.

Minimum Window Substring

Problem (LeetCode 76, hard): the smallest substring of s that contains every character of t (including duplicates).
s = "ADOBECODEBANC", t = "ABC" → "BANC".

Idea:

  1. Count what we need from t.
  2. Expand right. Track how many required characters are fully satisfied (formed).
  3. When every required character is satisfied, the window is valid: record it, then shrink from the left as far as possible while it stays valid.
TypeScript
function minWindow(s: string, t: string): string {
  if (t.length === 0 || t.length > s.length) return "";
  const need = new Map<string, number>();
  for (const ch of t) need.set(ch, (need.get(ch) ?? 0) + 1);

  const have = new Map<string, number>();
  const required = need.size;
  let formed = 0;
  let left = 0;
  let bestStart = 0;
  let bestLength = Infinity;

  for (let right = 0; right < s.length; right++) {
    const ch = s[right]!;
    have.set(ch, (have.get(ch) ?? 0) + 1);
    if (need.has(ch) && have.get(ch) === need.get(ch)) formed++;

    while (formed === required) {
      if (right - left + 1 < bestLength) {
        bestLength = right - left + 1;
        bestStart = left;
      }
      const leftCh = s[left]!;
      have.set(leftCh, have.get(leftCh)! - 1);
      if (need.has(leftCh) && have.get(leftCh)! < need.get(leftCh)!) formed--;
      left++;
    }
  }
  return bestLength === Infinity ? "" : s.slice(bestStart, bestStart + bestLength);
}

O(|s| + |t|) time, O(k) space for k distinct characters. In the interview, first explain the template, then the formed counter, which avoids comparing whole maps every step.

Longest vs shortest

GoalWhen to shrinkWhen to record the answer
Longest valid windowWhile the window is invalidAfter shrinking (window is valid)
Shortest valid windowWhile the window is validInside the shrinking loop, before removing

How to say it in an interview

"For variable windows I expand right one step at a time and shrink left while a condition holds, keeping counts in a map. For the longest valid window I shrink while invalid and record after; for the shortest I record and shrink while still valid. Each index enters and leaves the window once, so it is O(n). For Longest Substring Without Repeating Characters I store last indexes and jump left past repeats inside the window; for Minimum Window Substring I track how many required characters are fully satisfied."

Key words

WordMeaning
Variable windowA window that grows and shrinks
Expand / shrinkMove the right edge / the left edge
Valid windowA window that meets the problem's condition
formedA count of requirements currently met

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.