LeetCode Collections: Interview Problems from Naive to Optimal / Module 03

Module 3: Sliding Window

Work four sliding-window problems as spoken interviews, from checking every substring to one pass where neither pointer moves back.

Here is a first answer to 3. Longest Substring Without Repeating Characters: check every substring for a repeated character, and keep the length of the longest clean one.

function hasNoRepeats(s: string, from: number, to: number): boolean {
  const seen = new Set<string>();
  for (let i = from; i <= to; i++) {
    if (seen.has(s[i])) return false;
    seen.add(s[i]);
  }
  return true;
}

// O(n³) time: checks every substring from scratch (O(n² · σ) when the alphabet has σ characters,
// because a check stops at the first repeat). O(min(n, σ)) memory for the set.
export function lengthOfLongestSubstringBrute(s: string): number {
  let best = 0;
  for (let start = 0; start < s.length; start++) {
    for (let end = start; end < s.length; end++) {
      if (hasNoRepeats(s, start, end)) best = Math.max(best, end - start + 1);
    }
  }
  return best;
}

The comment uses σ (sigma), the size of the alphabet: the set of characters the string can hold. LeetCode allows strings of up to 10⁵ characters. In one run these loops took 593.81 ms at 2,000 characters and grew about 4 times per doubling. So 10⁵ characters would take about 25 minutes (an estimate from that growth). A sliding window took 45.33 ms at 2,000,000 characters.

This module works four problems where a run of consecutive items, marked by two indexes that only move forward, replaces a check of every substring or every pair. Each one follows the nine steps from Module 1, from the naive solution to the optimal one.

After this module, you can:

  • spot a sliding-window problem: the longest or shortest run of consecutive items that obeys a rule
  • grow a window with right, shrink it with left, and say why neither pointer ever moves back
  • keep what the window holds (a set, last positions, letter counts, a count of missing letters) up to date in O(1) per step, instead of recounting
  • read the alphabet size in the limits, and say when a solution that costs σ per step is fast enough

The code for this module is in module-03/ of the course repository, and node --test "module-03/**/*.test.ts" from its root runs every test. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.

The pattern: a window that grows on the right and shrinks on the left

In Module 2, two pointers started at the two ends and moved toward each other. Here both start at the left and move the same way. A sliding window is a run of consecutive items between two indexes, left and right, that each only move forward. DSA Module 2 teaches it, and DSA Module 3 teaches the Map and Set that hold what is inside the window.

Each step, right adds one item. When the window breaks the problem’s rule, left drops items until it obeys the rule again. Neither pointer moves back, so together they make at most 2n moves, even though the code has a loop inside a loop.

Signs that point to this pattern:

  • the longest or shortest substring or subarray: consecutive items, not any subset
  • a rule about the items inside: no repeats, at most k changes, holds every letter of another string
  • a window that breaks the rule stays broken when it grows (for “longest”), or a window that obeys it still obeys when it grows (for “shortest”)
  • a best pair where one item must come before the other, so the best left end can be carried forward

The cost is that the rule must behave that way. If adding an item could fix a broken window, dropping items from the left might throw away the answer, and the window would return wrong results. And the window needs a small structure that changes in O(1) when one item enters or leaves.

Rule: If a window that breaks the rule stays broken as it grows, move left forward until it’s fine, and never move either pointer back.

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock is rated Easy. You get one price per day, and you may buy once and sell once, on a later day. You return the largest gain you can make, or 0 if no later price is higher.

  • 1 ≤ n ≤ 10^5 (n = prices.length)
  • 0 ≤ prices[i] ≤ 10^4

The signature is function maxProfit(prices: number[]): number. Try it on LeetCode first.

Hint

For one sell day, the best buy day is the cheapest day before it. Can you carry that day forward instead of searching for it again?

Interviewer: Here’s a list of daily prices. What’s the most you can earn from one trade?

Candidate: I buy on one day and sell on a later day, and I return the largest difference. Can the list be empty?

Interviewer: No, there’s at least one day.

Candidate: With one day there’s no sale, so I return 0. And if prices only fall, do I return a loss?

Interviewer: No. If you can’t gain, you don’t trade, and the answer is 0.

Candidate: Are prices whole numbers, and can they be negative?

Interviewer: Whole numbers from 0 to 10,000.

Candidate: Then the largest gain is 10,000, so there’s no overflow to think about.

The interviewer and the candidate are invented. The problems, limits and timings are real.

Candidate: Here’s my example, and three edge cases.

prices               expected
[3, 8, 2, 5, 1, 4]   5        buy at 3, sell at 8
[5]                  0        one day: no sale
[9, 7, 4]            0        only falls
[2, 9, 1]            7        the lowest price comes last

Pause and predict. In the Candidate’s example, the lowest price is 1, on day 4. Is day 4 the best day to buy?

Candidate: No. After day 4 the best price is 4, so buying at 1 gains only 3. Buying at 3 and selling at 8 gains 5. The lowest price isn’t always the buy day, because the sale has to come after it.

Candidate: The naive solution tries every pair of buy and sell days.

// O(n²) time: tries every (buy, sell) pair. O(1) memory.
export function maxProfitBrute(prices: number[]): number {
  let best = 0;
  for (let buy = 0; buy < prices.length; buy++) {
    for (let sell = buy + 1; sell < prices.length; sell++) {
      best = Math.max(best, prices[sell] - prices[buy]);
    }
  }
  return best;
}

Candidate: That’s n(n – 1)/2 pairs, so O(n²) time and O(1) memory. At 10⁵ days it’s about 5 × 10⁹ pairs, 50 times the budget from Module 1, so it’s too slow.

atlimit.ts in the module folder times one call of each naive and final solution at LeetCode’s limit. One call is a rough number, and yours will differ. At 100,000 prices, maxProfitBrute took 2,961.9 ms.

Interviewer: Where’s the repeated work?

Candidate: For each sell day, the inner loop looks back at every earlier day, and all it needs from them is the cheapest one. The next sell day looks back over the same days again, plus one.

Candidate: So I keep the cheapest day so far as buy, the left edge of a window, and move sell, the right edge, one day at a time. If today is cheaper than buy, today becomes the new buy. Otherwise I check the gain from selling today.

// O(n) time: each day is the sell day once, and the buy day only moves forward. O(1) memory.
function maxProfit(prices: number[]): number {
  let buy = 0;
  let best = 0;
  for (let sell = 1; sell < prices.length; sell++) {
    if (prices[sell] < prices[buy]) {
      buy = sell; // a cheaper day: every later sale does better buying here
    } else {
      best = Math.max(best, prices[sell] - prices[buy]);
    }
  }
  return best;
}

export { maxProfit };

Candidate: When buy moves, it never moves back. Every later sale does at least as well buying on the cheaper day, so the old day can’t be in a better answer.

Interviewer: Walk me through your example.

Figure 1 traces the Candidate’s example. The buy column shows the buy day before the step, with its price.

prices  [3] [8] [2] [5] [1] [4]
         0   1   2   3   4   5

sell  price  buy (price)  what happens              best
1     8      0 (3)        8 - 3 = 5                    5
2     2      0 (3)        2 is cheaper: buy = 2        5
3     5      2 (2)        5 - 2 = 3                    5
4     1      2 (2)        1 is cheaper: buy = 4        5
5     4      4 (1)        4 - 1 = 3                    5
                          return 5

Figure 1: buy always holds the cheapest day before sell, so one pass tries the best buy day for every sell day.

Candidate: For [2, 9, 1], day 1 gives 9 – 2 = 7. Then 1 is cheaper, so buy moves to day 2, but no day comes after it. The answer stays 7. For [5], the loop never runs, and I return 0.

Interviewer: Final cost?

Candidate: O(n) time: one pass, and buy only moves forward. O(1) memory: two indexes and the best gain.

At 100,000 prices, maxProfit took 1.3 ms, against 2,961.9 ms for every pair.

This window is the smallest one in the module. Its left edge doesn’t shrink step by step; it jumps straight to a cheaper day. But the reason it’s safe is the one every window here uses: once left passes a position, no better answer can start there.

Interviewer: What if you may buy and sell as many times as you like, holding one share at a time?

The Candidate’s answer

Candidate: Then I add up every rise from one day to the next. A long rise from 2 to 9 earns the same as the small rises inside it, and I never need to hold through a fall. For my example that’s 5 + 3 + 3 = 11. It’s O(n) time and O(1) memory.

That’s LeetCode’s 122. Best Time to Buy and Sell Stock II, which this course doesn’t cover. A scratch run compared this sum with a brute force that tries every plan, on 3,000 random lists, and they always agreed. The code isn’t in the lab.

Interviewer: What if the prices arrive one at a time, as a stream?

The Candidate’s answer

Candidate: The loop already reads each price once, in order. I keep the cheapest price seen and the best gain, and update both when a price arrives. That’s O(1) memory, and the gain so far is always ready.

Interviewer: Can you see this as a problem about sums?

The Candidate’s answer (stretch)

Candidate: Yes. Buying on day i and selling on day j gains the sum of the day-to-day changes from i to j. So the answer is the largest sum of consecutive changes, or 0. For my example the changes are 5, -6, 3, -4, 3, and the largest sum is the first one, 5.

That’s the maximum subarray problem, and Module 12 works it as 53. Maximum Subarray. A scratch run compared this view with maxProfit on 20,000 random lists, and they always agreed.

Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module.

  • Highest price minus lowest price. That ignores the order of the days. For the Candidate’s example it returns 7 (8 – 1) instead of 5. The sale must come after the buy.
  • Starting best below 0. A version that starts best at -Infinity and records the change on every day reports a loss. For [9, 7, 4] it returns -2, and for [5] it returns -Infinity, instead of 0 for both. Start best at 0.

Lab folder: module-03/0121-best-time-to-buy-and-sell-stock/ in the course repository.

3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters is rated Medium. You get a string and return the length of the longest run of consecutive characters in which no character appears twice. Characters picked with gaps between them don’t count as a run.

  • 0 ≤ n ≤ 10^5 (n = s.length)
  • s holds English letters, digits, symbols and spaces

The signature is function lengthOfLongestSubstring(s: string): number. Try it on LeetCode first.

Hint

When the character at right is already in the window, which starts can you rule out for good?

Interviewer: Find the longest substring with no repeated character.

Candidate: So a run of consecutive characters, and I return its length, not the substring. Can the string be empty?

Interviewer: Yes. Then the answer is 0.

Candidate: Which characters can appear? And are a and A different?

Interviewer: Letters, digits, symbols and spaces. a and A are different characters, and a space is a character like any other.

Candidate: So the alphabet is small and fixed. That matters for the cost, so I’ll keep it in mind as σ.

Candidate: Here are my cases.

s             expected
"cadbzabcd"   5        "cadbz", and also "zabcd"
""            0        empty
"abcdef"      6        the whole string: count the last window
"abba"        2        the second a's copy is already out of the window

Candidate: The naive solution checks every substring with a fresh set.

The Candidate writes lengthOfLongestSubstringBrute, the function at the top of this page.

Candidate: There are about n²/2 substrings, and each check reads up to n characters, so O(n³) time in general. But a check stops at the first repeat, and with σ characters a repeat comes within σ + 1 of them. So it’s O(n² · σ). Either way, at 10⁵ characters that’s at least 5 × 10⁹ steps, far over the budget.

Interviewer: What does it repeat?

Candidate: Two things. If a substring has a repeat, every longer substring from the same start has it too, but I keep checking them. And each check rereads characters the previous check already read.

Candidate: The first one is easy to fix. From each start, I add characters to a set until one repeats, and then I go to the next start.

// O(n · min(n, σ)) time: grows from each start and stops at the first repeat,
// so each start costs at most σ + 1 steps. O(min(n, σ)) memory.
export function lengthOfLongestSubstringGrow(s: string): number {
  let best = 0;
  for (let start = 0; start < s.length; start++) {
    const seen = new Set<string>();
    let end = start;
    while (end < s.length && !seen.has(s[end])) {
      seen.add(s[end]);
      end++;
    }
    best = Math.max(best, end - start);
  }
  return best;
}

Candidate: Each start stops within σ + 1 characters, so this is O(n · σ). If “letters, digits, symbols and spaces” means printable ASCII, σ is under a hundred. Then 10⁵ characters take under 10⁷ steps, so it fits.

In the measurement at the end of this page, this version took 79.25 ms at 200,000 characters. With an alphabet as large as the input, it would be O(n²). Saying so out loud tells the interviewer you read the limits.

Interviewer: It fits. Can you get rid of σ?

Candidate: Each start still rebuilds a set the previous start almost had. If the run from start stopped at a repeat, the run from start + 1 holds the same characters minus one.

Candidate: So I keep one window. right adds a character each step. If that character is already in the window, I drop characters from the left until its earlier copy is gone.

// O(n) time: each character enters the window once and leaves it at most once. O(min(n, σ)) memory.
export function lengthOfLongestSubstringSet(s: string): number {
  const inWindow = new Set<string>();
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    while (inWindow.has(s[right])) {
      inWindow.delete(s[left]);
      left++;
    }
    inWindow.add(s[right]);
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Candidate: When s[right] repeats, no window that starts at or before its earlier copy can be clean, so dropping those starts for good is safe. Each character enters once and leaves at most once, so that’s at most 2n set operations: O(n).

Interviewer: The inner loop drops one character at a time. Can left jump?

Candidate: Yes, if I know where the earlier copy is. I keep a Map from each character to the last index where I saw it, and move left to one past that index.

Pause and predict. In "cadbzabcd", when right reaches the c at index 7, the window is "zab", from index 4 to 6. The last c was at index 0. Where should left go?

Candidate: Nowhere. Index 0 is already outside the window, so that c isn’t a repeat inside it. I only jump when the last index is at or after left.

// O(n) time: one pass; left jumps past the last copy of the repeated character. O(min(n, σ)) memory.
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 previous = lastIndex.get(s[right]);
    if (previous !== undefined && previous >= left) {
      left = previous + 1;
    }
    lastIndex.set(s[right], right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}

export { lengthOfLongestSubstring };

Interviewer: Trace it.

Figure 2 shows each step on "cadbzabcd", with the window after the step.

s  [c] [a] [d] [b] [z] [a] [b] [c] [d]
    0   1   2   3   4   5   6   7   8

right  char  last seen     left  window   length  best
0      c     -             0     c        1       1
1      a     -             0     ca       2       2
2      d     -             0     cad      3       3
3      b     -             0     cadb     4       4
4      z     -             0     cadbz    5       5
5      a     1             2     dbza     4       5
6      b     3             4     zab      3       5
7      c     0, < left     4     zabc     4       5
8      d     2, < left     4     zabcd    5       5

Figure 2: left jumps past an earlier copy only when that copy is inside the window, so left never moves back.

Candidate: For "abba", the second b moves left to 2. Then the last a was seen at 0, which is before left, so left stays at 2 and the answer is 2. For "abcdef", best is updated on every step, so the final window of 6 is counted.

Interviewer: Final cost?

Candidate: O(n) time: one pass, with O(1) average work per Map operation. O(min(n, σ)) memory, because the map holds one entry per different character.

Interviewer: What if the string holds emoji?

The Candidate’s answer

Candidate: Then s[i] is wrong. It reads one UTF-16 code unit, and an emoji is a code point that takes two. In one run, lengthOfLongestSubstring("\u{1F600}\u{1F601}") returned 3, although the string holds two different characters: the two emoji start with the same code unit.

Candidate: The fix is to walk code points. I’d run the same loop over [...s], which splits the string by code point, at the cost of an array of n strings.

Interviewer: What if the string holds only lowercase letters?

The Candidate’s answer

Candidate: Then I replace the Map with an array of 26 last positions, indexed by charCodeAt(i) - 97. It’s still O(n), with a smaller constant, and the answer is at most 26.

Interviewer: What if I want the substring, not its length?

The Candidate’s answer

Candidate: I keep bestStart and update it together with best. At the end I return s.slice(bestStart, bestStart + best). Same cost.

Two mistakes are common here:

  • Jumping without the previous >= left check. left then moves back when the earlier copy is outside the window. For "abba" that version returns 3 instead of 2. Jump only to a copy inside the window.
  • Updating best only when a repeat is found. The last window is never counted. For "abc" that version returns 0 instead of 3. Update best on every step.

Lab folder: module-03/0003-longest-substring-without-repeating-characters/ in the course repository.

424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement is rated Medium. You get a string of capital letters and a number k, and you may change at most k letters, each to any capital letter. You return the length of the longest run of consecutive positions that can be made into one repeated letter.

  • 1 ≤ n ≤ 10^5 (n = s.length)
  • s holds only uppercase English letters
  • 0 ≤ k ≤ n

The signature is function characterReplacement(s: string, k: number): number. Try it on LeetCode first.

Hint

To turn a window into one letter, keep its most common letter and change the rest. How many changes is that?

Interviewer: You may change up to k letters. How long a run of one letter can you make?

Candidate: I pick a run of consecutive positions and change at most k of its letters so they’re all the same. I return the longest such run. Can k be 0?

Interviewer: Yes. And k can be as large as the string.

Candidate: Then with k = 0 the answer is the longest run of one letter, and with k ≥ n it’s the whole string. Do I have to use all k changes?

Interviewer: No, at most k.

Candidate: Only A to Z? Then 26 counts are enough.

Interviewer: Only capitals.

Candidate: One fact first. The cheapest way to make a window one letter is to keep its most common letter and change the others. So a window works if its length minus the count of its most common letter is at most k.

Candidate: Here are my cases.

s           k   expected
"BAAACAB"   1   5        "AAACA": change the C
"ABBBCC"    0   3        no changes: the longest run, "BBB"
"ABC"       3   3        k covers the whole string
"QQQQ"      2   4        nothing to change

Candidate: The naive solution grows from each start and keeps 26 counts and the top count as it goes, so each window costs O(1) to check.

const A = "A".charCodeAt(0);

// O(n²) time: grows from each start, keeping letter counts and the top count as it goes. O(1) memory (26 counts).
export function characterReplacementBrute(s: string, k: number): number {
  let best = 0;
  for (let start = 0; start < s.length; start++) {
    const counts = new Array(26).fill(0);
    let topCount = 0;
    for (let end = start; end < s.length; end++) {
      const letter = s.charCodeAt(end) - A;
      counts[letter]++;
      topCount = Math.max(topCount, counts[letter]);
      const length = end - start + 1;
      if (length - topCount <= k) best = Math.max(best, length);
    }
  }
  return best;
}

Candidate: That’s n(n + 1)/2 windows at O(1) each, so O(n²) time, and O(1) memory for 26 counts. At 10⁵ letters it’s about 5 × 10⁹ steps, too slow. Recounting each window from scratch would even be O(n³).

At 100,000 letters with k = 1,000, characterReplacementBrute took 11,593.6 ms.

Interviewer: What does it repeat?

Candidate: Each start rebuilds counts the previous start almost had. And once a window from start needs more than k changes, every longer window from that start needs at least as many.

Candidate: It’s the same shape as the last problem. right adds a letter. While the window needs more than k changes, left drops a letter. Every longer window that ends at right needs at least as many changes, so left never has to move back.

// O(26 · n) time: a window that shrinks while it needs more than k changes,
// finding the top count by scanning all 26 letters. O(1) memory.
export function characterReplacementRecount(s: string, k: number): number {
  const counts = new Array(26).fill(0);
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    counts[s.charCodeAt(right) - A]++;
    while (right - left + 1 - Math.max(...counts) > k) {
      counts[s.charCodeAt(left) - A]--;
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Candidate: Each check scans 26 counts, so it’s O(26 · n) time, about 5 × 10⁶ steps at the limit. That fits.

At the limit, characterReplacementRecount took 8.6 ms. In an interview this is a good answer to stop at. It’s easy to explain and easy to get right.

Interviewer: It fits. Can you drop the scan of 26 counts?

Candidate: I’ll keep topCount, the largest count any letter has reached in the window, and update it only from the letter that entered. When a letter leaves, I don’t lower it.

Candidate: And the window never shrinks. If it needs more than k changes, I move left once, so the window slides with the same length. Its length then always equals the best answer so far.

// O(n) time: the window only grows or slides, and the top count is never lowered,
// because only a higher top count can give a longer answer. O(1) memory.
function characterReplacement(s: string, k: number): number {
  const counts = new Array(26).fill(0);
  let topCount = 0;
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    const letter = s.charCodeAt(right) - A;
    counts[letter]++;
    topCount = Math.max(topCount, counts[letter]);
    if (right - left + 1 - topCount > k) {
      counts[s.charCodeAt(left) - A]--;
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

export { characterReplacement };

Interviewer: Show me on your example.

Figure 3 traces "BAAACAB" with k = 1. The length - top column uses the length after right adds its letter, before any slide.

s  [B] [A] [A] [A] [C] [A] [B]      k = 1
    0   1   2   3   4   5   6

right  letter  count  topCount  length - top  move           window  best
0      B       1      1         1 - 1 = 0     grow           B       1
1      A       1      1         2 - 1 = 1     grow           BA      2
2      A       2      2         3 - 2 = 1     grow           BAA     3
3      A       3      3         4 - 3 = 1     grow           BAAA    4
4      C       1      3         5 - 3 = 2     slide, drop B  AAAC    4
5      A       4      4         5 - 4 = 1     grow           AAACA   5
6      B       1      4         6 - 4 = 2     slide, drop A  AACAB   5

Figure 3: the window grows only when topCount rises, so its length is always the best answer found so far.

Pause and predict. After step 6, the window is "AACAB" and topCount is still 4. Can "AACAB" be made into one letter with one change?

Candidate: No. Its most common letter is A, three times, so it needs two changes. topCount is out of date. But the function returns the length, 5, and a window of length 5 did work at step 5, so the answer is still right.

Interviewer: Why is it safe never to lower topCount?

Candidate: Before the first slide, nothing has left the window, so topCount is exact. After that, the window grows only at a step where a count beats topCount. That count belongs to the letter that entered at that step, so it’s real, and the grown window works.

The other half is that no answer is missed. After the first slide, the window’s length is topCount + k, so a longer window would need a letter with at least topCount + 1 copies. Keeping the old, higher topCount can only delay growth, and it can’t report a length that no window reaches. The lab checks this version against the brute force on 300 random strings in the tests, and a scratch run checked 20,000 more, with no difference.

Candidate: For "ABBBCC" with k = 0, the window reaches "BBB" at step 3. No letter beats 3 after that, so the window slides to "BBC" and "BCC", and the answer stays 3.

Interviewer: Final cost?

Candidate: O(n) time: one pass, O(1) per step. O(1) memory: 26 counts and three numbers.

At the limit, characterReplacement took 1.7 ms, against 8.6 ms for the recount and 11,593.6 ms for the naive solution.

Interviewer: What if the string can hold any characters, not only capitals?

The Candidate’s answer

Candidate: I’d count in a Map instead of 26 slots. The final version stays O(n), because it only reads the count of the letter that entered. The recount version becomes O(σ · n), because it scans every count.

Interviewer: Is there another way to think about it?

The Candidate’s answer

Candidate: I can try each of the 26 letters as the letter to keep. For one letter, I find the longest window with at most k other letters, which is the same growing window. That’s 26 passes, O(26 · n) time, and O(1) memory. It’s the easiest version to prove, but this one isn’t in the lab.

Two mistakes are common here:

  • Sliding when the window needs exactly k changes. A window that needs k changes is allowed. With >= k instead of > k, "BAAACAB" with k = 1 returns 3 instead of 5, and "AAA" with k = 0 returns 0 instead of 3. Slide only when the window needs more than k.
  • Keeping the letter at the left edge. A version that counts changes against s[left] doesn’t keep the most common letter. For "ABBB" with k = 1 it returns 3 instead of 4, because the best plan changes the A. Count against the most common letter.

Lab folder: module-03/0424-longest-repeating-character-replacement/ in the course repository.

76. Minimum Window Substring

76. Minimum Window Substring is rated Hard. You get two strings, s and t, and find the shortest run of consecutive characters in s that holds every character of t, counting repeats: if t has two as, the run needs two. You return that run, or the empty string if there is none.

  • m = s.length, n = t.length, 1 ≤ m, n ≤ 10^5
  • s and t hold uppercase and lowercase English letters
  • the tests have a unique answer
  • follow-up on the page: can it run in O(m + n) time?

The signature is function minWindow(s: string, t: string): string. Try it on LeetCode first.

Hint

Grow the window until it holds everything t needs. Then shrink it from the left for as long as it still does.

Interviewer: Find the shortest part of s that contains all of t.

Candidate: A run of consecutive characters in s that holds every character of t. If t has a letter twice, does the run need it twice?

Interviewer: Yes. Every copy counts.

Candidate: Are a and A different? And what if no run works?

Interviewer: They’re different letters. If nothing works, return the empty string.

Candidate: What if two shortest runs exist?

Interviewer: The tests promise a unique answer.

Candidate: Then the first shortest window I find is the answer. Here are my cases.

s           t       expected
"XAYBZAXB"  "ABX"   "AXB"    "XAYB" and "BZAX" cover t too, with length 4
"ab"        "abc"   ""       t is longer than s
"aabcab"    "aab"   "aab"    t needs two a's
"aBcA"      "AB"    "BcA"    case matters

Candidate: The naive solution starts at each position and grows until the window covers t. I count t’s letters in a map, and check a window by comparing counts.

function countLetters(t: string): Map<string, number> {
  const need = new Map<string, number>();
  for (const ch of t) need.set(ch, (need.get(ch) ?? 0) + 1);
  return need;
}

function covers(have: Map<string, number>, need: Map<string, number>): boolean {
  for (const [ch, count] of need) {
    if ((have.get(ch) ?? 0) < count) return false;
  }
  return true;
}

// O(m² · σ) time: from each start, grows until the window covers t, checking every needed
// letter (σ of them) at each step. O(σ) memory.
export function minWindowBrute(s: string, t: string): string {
  const need = countLetters(t);
  let bestStart = 0;
  let bestLength = Infinity;
  for (let start = 0; start < s.length; start++) {
    const have = new Map<string, number>();
    for (let end = start; end < s.length; end++) {
      have.set(s[end], (have.get(s[end]) ?? 0) + 1);
      if (covers(have, need)) {
        if (end - start + 1 < bestLength) {
          bestStart = start;
          bestLength = end - start + 1;
        }
        break; // a longer window from this start cannot be shorter
      }
    }
  }
  return bestLength === Infinity ? "" : s.slice(bestStart, bestStart + bestLength);
}

Candidate: From each start, the first covering end gives the shortest window for that start, so I stop there. In the worst case no window covers t, and each start runs to the end: about m²/2 steps, each checking up to σ = 52 letters. At m = 10⁵ that’s over 5 × 10⁹ steps, so it’s too slow.

Interviewer: What does it repeat?

Candidate: Each start rebuilds the counts from scratch. And once a window from left to right covers t, a window that starts earlier and ends at right is only longer, so I never need to look back.

Candidate: So it’s a window again, but it shrinks while it’s good, not while it’s broken. right adds a letter. While the window covers t, I record it and drop the letter at left.

// O(σ · m + n) time: a sliding window, but each step re-checks every needed letter. O(σ) memory.
export function minWindowRecheck(s: string, t: string): string {
  const need = countLetters(t);
  const have = new Map<string, number>();
  let left = 0;
  let bestStart = 0;
  let bestLength = Infinity;
  for (let right = 0; right < s.length; right++) {
    have.set(s[right], (have.get(s[right]) ?? 0) + 1);
    while (covers(have, need)) {
      if (right - left + 1 < bestLength) {
        bestStart = left;
        bestLength = right - left + 1;
      }
      have.set(s[left], have.get(s[left])! - 1);
      left++;
    }
  }
  return bestLength === Infinity ? "" : s.slice(bestStart, bestStart + bestLength);
}

Candidate: Each pointer moves at most m times, and each check scans up to σ needed letters. That’s O(σ · m + n), about 5 × 10⁶ steps at the limit, so it fits.

At the limit, with a t of 50 letters, minWindowRecheck took 55.1 ms.

Interviewer: The page asks for O(m + n). Your check still costs σ.

Candidate: With 52 letters, σ is a constant, so strictly this is already O(m + n). But the check doesn’t need to look at every letter. Only one count changes per step, so I can keep one number up to date.

Candidate: need holds how many of each letter the window still lacks; it goes below 0 when the window has spare copies. missing counts the letters of t, with repeats, that aren’t in the window yet. The window covers t exactly when missing is 0.

Candidate: A letter entering lowers missing only if the window still needed it. A letter leaving raises missing only if its count goes back above 0, which means the window no longer has enough.

// O(m + n) time: each index enters and leaves the window once, and `missing` says in O(1)
// whether the window covers t. O(σ) memory.
function minWindow(s: string, t: string): string {
  const need = countLetters(t);
  let missing = t.length; // letters of t, with repeats, not yet in the window
  let left = 0;
  let bestStart = 0;
  let bestLength = Infinity;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (need.has(ch)) {
      if (need.get(ch)! > 0) missing--;
      need.set(ch, need.get(ch)! - 1); // below 0 means the window holds a spare copy
    }
    while (missing === 0) {
      if (right - left + 1 < bestLength) {
        bestStart = left;
        bestLength = right - left + 1;
      }
      const out = s[left];
      if (need.has(out)) {
        need.set(out, need.get(out)! + 1);
        if (need.get(out)! > 0) missing++;
      }
      left++;
    }
  }
  return bestLength === Infinity ? "" : s.slice(bestStart, bestStart + bestLength);
}

export { minWindow };

Interviewer: Trace your example.

Figure 4 traces minWindow("XAYBZAXB", "ABX"). missing starts at 3, and each row shows it after right adds its letter. The last column shows the windows checked while missing is 0.

s  [X] [A] [Y] [B] [Z] [A] [X] [B]      t = "ABX"
    0   1   2   3   4   5   6   7

right  adds  missing  while missing is 0                       best
0      X     2
1      A     1
2      Y     1        (Y is not in t)
3      B     0        XAYB (4) is the best so far;             XAYB
                      drop X: missing 1
4      Z     1
5      A     1        a spare A: need[A] goes to -1
6      X     0        AYBZAX (6), YBZAX (5), BZAX (4)          XAYB
                      are not shorter; drop A (spare), Y,
                      then B: missing 1
7      B     0        ZAXB (4), then AXB (3) is the best;      AXB
                      drop Z, then A: missing 1
                      return "AXB"

Figure 4: missing is 0 exactly when the window covers t, and each index enters and leaves the window once.

Candidate: At step 6, dropping the first A doesn’t raise missing, because the window still holds the second A. That’s what the spare count is for. BZAX has length 4, the same as XAYB, so I keep the earlier one.

Candidate: For "aabcab" and "aab", need starts as a: 2, b: 1. The window first covers t at "aab", and dropping the first a raises missing. Nothing shorter appears later, so the answer is "aab".

Interviewer: Final cost?

Candidate: O(m + n) time: O(n) to count t, then each index of s enters and leaves the window once, with O(1) work each time. O(σ) memory for need, at most 52 entries.

At the limit, minWindow took 6.7 ms, against 55.1 ms for the version that rechecks every letter.

Interviewer: What if I want the start and end indexes instead?

The Candidate’s answer

Candidate: I return [bestStart, bestStart + bestLength - 1], or [-1, -1] when no window covers t. Same cost.

Interviewer: What if s is huge, and only a few of its characters appear in t?

The Candidate’s answer

Candidate: First I list the positions in s whose character is in t. Then I slide the window over that list, and use the positions to measure each window’s length. It’s still O(m + n), but the window only steps over characters that matter. This version isn’t in the lab.

Two mistakes are common here:

  • A set of t’s letters. A set ignores repeats, so the window needs each letter only once. For s = "aabcab" and t = "aab", that version returns "ab" instead of "aab". Count each letter.
  • Lowering missing for a spare copy. If every needed letter lowers missing, a second A counts as the B. For s = "XAAYB" and t = "AB", that version returns "AA" instead of "AYB". Lower missing only while the letter’s count is above 0.

Lab folder: module-03/0076-minimum-window-substring/ in the course repository.

Measured: Longest Substring, every substring against the window

Longest Substring Without Repeating Characters is the problem this module measures, with bench.ts from DSA Module 1. The brute force runs at 500, 1,000 and 2,000 characters, because it takes over half a second at 2,000. Growing from each start and the window with last positions run at 2,000 up to 2,000,000. Each character is drawn at random from the 95 printable ASCII characters, from the space to ~.

// measure.ts: 3. Longest Substring Without Repeating Characters, every substring against the window.
// Run from the repository root: node module-03/measure.ts
import { bench } from "../shared/bench.ts";
import {
  lengthOfLongestSubstringBrute,
  lengthOfLongestSubstringGrow,
  lengthOfLongestSubstring,
} from "./0003-longest-substring-without-repeating-characters/solution.ts";

// The 95 printable ASCII characters, space to "~": letters, digits, symbols and spaces.
const alphabet = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join("");

function randomText(n: number): string {
  const chars: string[] = [];
  for (let i = 0; i < n; i++) chars.push(alphabet[Math.floor(Math.random() * alphabet.length)]);
  return chars.join("");
}

let sink = 0;

bench("every substring (brute)", [500, 1_000, 2_000], randomText, (s) => {
  sink += lengthOfLongestSubstringBrute(s);
});
bench("grow from each start", [2_000, 20_000, 200_000, 2_000_000], randomText, (s) => {
  sink += lengthOfLongestSubstringGrow(s);
});
bench("sliding window (last index)", [2_000, 20_000, 200_000, 2_000_000], randomText, (s) => {
  sink += lengthOfLongestSubstring(s);
});

console.log(`\nsink ${sink}`);

bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before.

Pause and predict. The brute force is O(n² · σ) with a fixed σ. When n doubles, how many times longer should it take? And when n grows 10 times, how much longer should the window take?

Here is what node module-03/measure.ts printed:


every substring (brute)
             n   median ms   x prev
           500       36.18         
         1,000      151.78      4.2
         2,000      593.81      3.9

grow from each start
             n   median ms   x prev
         2,000        0.82         
        20,000        8.03      9.8
       200,000       79.25      9.9
     2,000,000      804.60     10.2

sliding window (last index)
             n   median ms   x prev
         2,000        0.06         
        20,000        0.46      7.2
       200,000        4.56      9.9
     2,000,000       45.33     10.0

sink 2587

These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.

The brute force grew 4.2 and 3.9 times per doubling, which is O(n²), not O(n³). With 95 characters, each check meets a repeat within a few characters, so σ stays a constant and the n² substrings set the growth. At 10⁵ characters, 2,500 times the work of 2,000 (50² for quadratic growth), it would take about 25 minutes. That’s an estimate, not a run.

Growing from each start grew about 10 times per 10 times the input, so it’s linear, because σ bounds the work per start. The window also grew 9.9 and 10.0 times; its first step, 7.2, is too small to read, since the times are under 1 ms. At 2,000,000 characters the window was about 18 times faster than growing from each start (45.33 against 804.60 ms). At 2,000 it was about 10,000 times faster than the brute force. sink is the total of every length returned, so V8 can’t skip the calls.

Underneath: what the window’s Set and Map do on each step

The window in this module is two indexes and a small structure that changes by one item at each edge. That structure costs something different in each solution.

The Set in lengthOfLongestSubstringSet deletes a character and adds one on every slide. In V8 13.6, the engine in Node.js 24.22.1, a delete marks the entry as deleted and leaves it in its slot. Each add writes a new entry after the last one, so deleted entries pile up behind the live ones.

When live and deleted entries fill the table, V8 rehashes: it copies the live entries into a new table. If at least half the slots hold deleted entries, the new table has the same size (ordered-hash-table.cc). So the window’s set stays within a few times the window’s size, but now and then a slide pays for a copy of the whole table.

The Map in lengthOfLongestSubstring never deletes. A set on a key that is already there replaces the value in its entry, so the map holds one entry per different character. DSA Module 3 draws the table with its deleted entries.

The 26 counts in Longest Repeating Character Replacement need no hashing at all, because a letter’s slot is charCodeAt(i) - 65. In one run on Node.js 24.22.1, new Array(26).fill(0) was a packed array of Smis, and it stayed one after counts[i]++. DSA Module 2 shows elements kinds.

Cheat sheet

Figure 5 maps each problem in this module to the sign that pointed to its solution.

sign in the problem                     problem  the window keeps    cost
best pair, buy before sell              121      the cheapest day    O(n)
longest run with no repeats             3        last index of each  O(n)
                                                 character
longest run, at most k changes          424      26 counts and the   O(n)
                                                 top count
shortest run that holds all of t        76       need counts and     O(m + n)
                                                 missing

Figure 5: when the rule over a run of consecutive items breaks in one direction only, two forward pointers replace the check of every run.

  • Pattern: right adds one item per step; left drops items while the window breaks the rule (longest) or obeys it (shortest). Neither moves back, so at most 2n moves.
  • Keep the state in O(1) per step: a set, last positions, counts, or one counter for “how much is missing”.
  • Read the alphabet: a small σ makes O(σ · n) fit (3’s grow, 424’s recount, 76’s recheck); the final versions drop σ.
  • Final costs: 121, 3 and 424 in O(n) time; 76 in O(m + n). Memory O(1) for 121 and 424, O(min(n, σ)) for 3, O(σ) for 76.
  • Next: Module 4 keeps items in a stack, and a stack whose values only rise or only fall finds the nearest larger or smaller item for every position in one pass.

Sources