Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in Rust: O(n + m) Sliding Window

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 18
    Ctrl + Enter to check

    RUST · SLIDING WINDOW

    Minimum Window Substring in Rust, explained

    Problem overview

    The function min_window 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. When no substring works, it returns an empty string. Uppercase and lowercase letters are different characters, and the tests are built so that the answer is unique.

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

    Approach: grow the window, then trim it

    Checking every substring of s against t would be far too slow for strings of 100,000 characters. A sliding window does it in one pass. The window is the substring from index first to index last:

    • last moves right one character at a time, adding to the window.
    • As soon as the window holds everything t needs, first moves right while the window can spare its first character, which makes it as short as possible for this last.
    • If the trimmed window is shorter than the best so far, remember where it starts and how long it is.

    Both ends only move right, so the time is O(n + m) for n = s.len() and m = t.len(). The extra space is one counter for each of the 128 ASCII codes, which is O(1).

    One counter per character

    The array need records how many more of each character the window still needs. It starts as the character counts of t. Adding a character to the window subtracts 1 from its count. So:

    • A count above 0 means the window still lacks some of that character.
    • A count of exactly 0 means the window has exactly as many as t asks for.
    • A count below 0 means the window holds extras, and the first of them can leave without breaking the window.

    A separate number, missing, starts as t.len() and drops by 1 only when a character that was still needed enters the window. When missing is 0, the window is complete, and checking that is a single comparison.

    Tracing s = "ADOBECODEBANC" with t = "ABC":

    lastcharmissingwindow after trimmingbest so far
    0A2Anone
    3B1ADOBnone
    5C0ADOBECADOBEC
    9B0ADOBECODEBADOBEC
    10A0CODEBAADOBEC
    12C0BANCBANC

    The window first becomes complete at index 5. At index 10 the new A lets the left end skip A, D, O, B and E, which leaves CODEBA, with length 6, so it doesn't beat ADOBEC. At index 12, the window trims down to BANC, with length 4.

    Step by step

    1. Get the bytes of s with as_bytes(), so characters can be read by index.
    2. Create need as [0i32; 128]. Letters have codes below 128, so uppercase and lowercase each get their own entry.
    3. Count t. Loop c over t.bytes() and add 1 to need[c as usize]. A letter that appears twice is needed twice.
    4. Set missing to t.len(): how many characters the window still lacks.
    5. Prepare the best window. first and best_start start at 0, and best_length starts at bytes.len() + 1. No window can be that long, so this value means that none has been found.
    6. Loop last over 0..bytes.len() and store the character's code in code.
    7. Update missing. If need[code] is above 0, the window needed this character, so subtract 1 from missing. Then subtract 1 from need[code] in every case.
    8. When missing == 0, trim from the left. While need[bytes[first] as usize] < 0, the window has an extra of its first character: give it back by adding 1 to its count and moving first right.
    9. Compare lengths. If last - first + 1 < best_length, save first as best_start and the length as best_length. Only the position and length are stored; the substring is cut once, at the end.
    10. No window found. After the loop, if best_length is still above bytes.len(), return String::new().
    11. Return the best window as a new String, with no semicolon.

    The solution in Rust

    impl Solution {
        fn min_window(s: String, t: String) -> String {
            let bytes = s.as_bytes();
            let mut need = [0i32; 128];
            for c in t.bytes() {
                need[c as usize] += 1;
            }
            let mut missing = t.len();
            let mut first = 0usize;
            let mut best_start = 0usize;
            let mut best_length = bytes.len() + 1;
            for last in 0..bytes.len() {
                let code = bytes[last] as usize;
                if need[code] > 0 {
                    missing -= 1;
                }
                need[code] -= 1;
                if missing == 0 {
                    while need[bytes[first] as usize] < 0 {
                        need[bytes[first] as usize] += 1;
                        first += 1;
                    }
                    if last - first + 1 < best_length {
                        best_start = first;
                        best_length = last - first + 1;
                    }
                }
            }
            if best_length > bytes.len() {
                return String::new();
            }
            s[best_start..best_start + best_length].to_string()
        }
    }
    

    The Rust details worth a closer look:

    • t.bytes() is an iterator of u8 values. A u8 can't index an array directly, so c as usize converts it.
    • Two integer types. need holds i32 values because it must go below zero. missing is a usize because it starts as t.len() and only reaches 0 when the window is complete. It never goes below 0, because it only drops when need[code] is positive.
    • Slicing a string. s[a..b] takes a byte range of the String and gives a str, and to_string() copies it into a new String. Rust panics if a range ends in the middle of a multi-byte character. With letters only, each character is one byte, so this can't happen.
    • Letters only. need[code] panics with an out-of-bounds index for a code of 128 or more, such as a character outside ASCII. The constraints guarantee English letters.
    • Early return. return String::new(); leaves the function at once. The final line has no semicolon, so it is the value the function returns otherwise.
    • Why first stays in range. Inside the while, the window is complete, so a character with a negative count really is in it. The loop therefore stops at or before last.

    Complexity

    Time: O(n + m). Counting t takes m steps. After that, last moves n times and first moves at most n times in total, each step costing a constant amount.

    Space: O(1) extra. The array has 128 entries, whatever the input. The returned string is a copy of the answer.

    Edge cases and common mistakes

    • No valid window. s = "a" with t = "aa" returns "", and so does s = "Ab" with t = "aB", because uppercase and lowercase letters are different.
    • Repeated characters in t. With s = "aaflslflsldkalskaaa" and t = "aaa" the answer is "aaa". Treating t as a set of letters instead of counts would accept a window with a single a.
    • The whole string. If s equals t up to order, as in "abc" and "cba", the answer is all of s.
    • Characters not in t. They have a count of 0, so adding one drops it to -1, and it is trimmed from the left when it reaches the front. It never changes missing.
    • Counting extras as progress. Subtracting 1 from missing without checking need[code] > 0 would count a third a toward a t that asks for two.
    • Trimming before the window is complete. The trim only runs when missing == 0. Before then, characters at the front are still needed.

    Testing

    • s = "ADOBECODEBANC", t = "ABC" gives "BANC".
    • s = "a", t = "a" gives "a".
    • s = "a", t = "aa" gives "".
    • s = "aab", t = "ab" gives "ab".
    • s = "ab", t = "b" gives "b".
    • s = "Ab", t = "aB" gives "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free