Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in C#: Sliding Window, O(n + m)

Practice O(n) Read the full explanation

You are given two strings s and t made of English letters. Return the shortest substring of s that contains every character of t, repeats included: if a letter appears twice in t, the substring must contain it at least twice.

If no substring of s contains all the characters of t, return an empty string, "". Uppercase and lowercase letters are different characters.

A substring is a run of consecutive characters of s. The tests are made so that the answer is unique.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: "BANC" contains an A, a B and a C, and no shorter substring contains all three. "ADOBEC" and "CODEBA" contain them too, but they are longer.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: s itself contains every character of t, and there is nothing shorter to try.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: t needs two a's, but s has only one, so no substring works. The expected output shows an empty line for it.

 

Constraints:

  • 1 <= s.length, t.length <= 105
  • s and t are made of uppercase and lowercase English letters only (a to z, A to Z).

Note:

Your algorithm should run in O(n + m) time, where n is the length of s and m the length of t, and use O(1) extra space: one count for each character code.

STEP 1 OF 17
    Ctrl + Enter to check

    C# · SLIDING WINDOW

    Minimum Window Substring in C#, explained

    Problem overview

    The method MinWindow receives two strings, s and t, made of English letters. It returns the shortest substring of s that contains every character of t, repeats included: if t has two a's, the substring needs at least two a's. If no substring qualifies, it returns an empty string. Uppercase and lowercase letters are different characters, and the tests are made so that the answer is unique.

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". The substrings "ADOBEC" and "CODEBA" also contain an A, a B and a C, but they are longer. For s = "a" and t = "aa" the answer is the empty string, because s has only one a.

    The target is O(n + m) time, where n and m are the lengths of s and t, and O(1) extra space: one counter for each character code.

    Approach: grow until complete, then shrink

    Checking every substring of s and counting its letters is far too slow for strings of 100,000 characters. A sliding window avoids the repeated work. The window is the part of s from index first to index last, and both ends only move right.

    1. Move last right, adding one character at a time, until the window contains everything t asks for.
    2. Once it is complete, move first right to drop every character the window can spare. What is left is the shortest complete window that ends at last. Compare it with the best so far.
    3. Keep moving last. The window stays complete, so the shrinking step runs again after each addition and finds shorter or equal candidates.

    The bookkeeping is a single array, need, with an entry for each character code. need[code] is how many more of that character the window still needs. At the start it holds the counts from t. Adding a character to the window subtracts 1 from its entry, and removing one adds 1. A positive entry means the window is still short of that character. A negative entry means the window holds more copies than t asks for, so one can leave without harm.

    A second variable, missing, starts at t.Length and counts how many needed characters the window still lacks. When it reaches 0, the window is complete. It only drops when a character is added whose need entry was positive, because an extra copy of something already covered doesn't help.

    Here is the run on s = "ADOBECODEBANC" and t = "ABC", showing the state after each step of last:

    last=0 'A' missing=2 first=0 best=""
    last=1 'D' missing=2 first=0 best=""
    last=2 'O' missing=2 first=0 best=""
    last=3 'B' missing=1 first=0 best=""
    last=4 'E' missing=1 first=0 best=""
    last=5 'C' missing=0 first=0 best="ADOBEC"
    last=6 'O' missing=0 first=0 best="ADOBEC"
    last=7 'D' missing=0 first=0 best="ADOBEC"
    last=8 'E' missing=0 first=0 best="ADOBEC"
    last=9 'B' missing=0 first=0 best="ADOBEC"
    last=10 'A' missing=0 first=5 best="ADOBEC"
    last=11 'N' missing=0 first=5 best="ADOBEC"
    last=12 'C' missing=0 first=9 best="BANC"
    

    At last = 5 the window "ADOBEC" becomes complete. At last = 10 a second A arrives, so the first A, and the characters after it that are now spare, can go, and first jumps to 5. The window "CODEBA" ties the best length, but it must be strictly shorter to replace it. At last = 12 the window shrinks to "BANC", which is shorter, and that becomes the answer.

    Step by step

    1. Create need as an int[] of size 128. Letters have codes below 128, so one entry per code covers a to z and A to Z, each case separately. A new array is filled with zeros.
    2. Count the characters of t with a foreach loop over its chars, adding 1 to need[c]. A letter that appears twice is needed twice.
    3. Set missing to t.Length. When it reaches 0 the window holds all of t.
    4. Declare first and bestStart as 0, then bestLength as s.Length + 1. No window can be that long, so this value means "none found yet".
    5. Loop last over s. Store s[last] in an int named code to get the character's code.
    6. If need[code] > 0, decrease missing. This copy was still needed. Then decrease need[code] either way: the window now holds one more of this character.
    7. When missing == 0, shrink from the left while need[s[first]] < 0. A negative entry means the first character is surplus. For each one dropped, add 1 back to its entry and move first right.
    8. Compare lengths. If last - first + 1 < bestLength, remember first as bestStart and the length as bestLength. Only two numbers are stored; the substring is cut once at the end.
    9. After the loop, return "" if bestLength is still above s.Length, otherwise s.Substring(bestStart, bestLength).

    The solution in C#

    class Solution {
        public string MinWindow(string s, string t) {
            int[] need = new int[128];
            foreach (char c in t) {
                need[c]++;
            }
            int missing = t.Length;
            int first = 0, bestStart = 0;
            int bestLength = s.Length + 1;
            for (int last = 0; last < s.Length; last++) {
                int code = s[last];
                if (need[code] > 0) missing--;
                need[code]--;
                if (missing == 0) {
                    while (need[s[first]] < 0) {
                        need[s[first]]++;
                        first++;
                    }
                    if (last - first + 1 < bestLength) {
                        bestStart = first;
                        bestLength = last - first + 1;
                    }
                }
            }
            if (bestLength > s.Length) return "";
            return s.Substring(bestStart, bestLength);
        }
    }
    

    The C# details worth knowing:

    • A char converts to int implicitly. int code = s[last]; stores the character's code, 65 for 'A' and 97 for 'a'. The same conversion lets need[c] use a char directly as an array index.
    • Array indexes are checked. A character whose code is 128 or more, such as an accented letter, would throw IndexOutOfRangeException here. The lesson guarantees plain English letters, so 128 is enough.
    • Substring(start, length) takes a length, not an end index. The second argument is how many characters to take. Code ported from Java, whose substring takes an end index, gets this wrong.
    • Strings are immutable. Substring creates a new string, which is why the code remembers only bestStart and bestLength during the loop and builds the result once at the end.
    • The one-line if and return without braces are legal C#, but only the single next statement belongs to the if.

    Complexity

    Time: O(n + m). Counting t takes m steps. The for loop runs n times, and the inner while only moves first to the right, so across the whole run it executes at most n times. The final Substring copies at most n characters once.

    Space: O(1) extra. The need array has a fixed size of 128, whatever the input. The returned string is the output, not working memory.

    Edge cases and common mistakes

    • No valid window. s = "a", t = "aa" and s = "abcdef", t = "z" both return "". missing never reaches 0, so bestLength keeps its starting value.
    • Repeats in t. Counting distinct letters instead of copies would accept a window with one a for t = "aa". Counting copies, as need does, avoids that.
    • Case matters. s = "AbC" with t = "abc" returns "", because 'A' and 'a' have different codes.
    • The whole string is the answer. s = "aa", t = "aa" returns "aa", and s = "aab", t = "aab" returns "aab".
    • The window can start late. s = "bba", t = "ab" returns "ba": the extra leading b is dropped by the shrinking loop.
    • Counting every character as missing. Decreasing missing without checking need[code] > 0 would count extra copies and report a complete window too early.
    • Shrinking before the window is complete. The while loop must run only when missing == 0. Otherwise it could drop characters the window still needs.
    • Using the length as an end index. s.Substring(bestStart, bestLength) is correct, while passing bestStart + bestLength as the second argument would take too many characters or throw.

    Testing

    • s = "ADOBECODEBANC", t = "ABC" gives "BANC".
    • s = "a", t = "a" gives "a".
    • s = "a", t = "aa" gives "".
    • s = "abc", t = "cba" gives "abc".
    • s = "ab", t = "b" gives "b".
    • s = "bba", t = "ab" gives "ba".
    • s = "AbC", t = "abc" gives "".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free