Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in Scala: 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 17
    Ctrl + Enter to check

    SCALA · SLIDING WINDOW

    Minimum Window Substring in Scala, explained

    Problem overview

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

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". The substrings "ADOBEC" and "CODEBA" also hold 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.

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

    Approach: grow until complete, then shrink as far as possible

    Trying every substring of s and counting its letters would take far too long for strings of 100,000 characters. A sliding window from index first to index last does it in one pass.

    The right end last moves across s one character at a time, and each character joins the window. Once the window holds every character t asks for, it is complete. A complete window stays complete as it grows, so there is no point in growing it further before looking at it. Instead the left end first moves right and drops every character the window can spare. What is left is the shortest complete window that ends at last. The code compares its length with the best one found so far and moves on.

    To know what the window can spare, the code keeps one counter per character code, need. It starts as the number of copies of each character that t contains. When a character enters the window, its counter goes down by one. A positive counter means the window still lacks copies of that character. A counter of zero means the window holds exactly the required number. A negative counter means the window holds extras, and one of them may leave without breaking it.

    A second variable, missing, starts at t.length and counts how many required characters the window still lacks. It drops by one only when a character that was still needed arrives, so a window is complete exactly when missing is 0. This avoids checking all the counters each time.

    Here is the trace for s = "ADOBECODEBANC" and t = "ABC", showing only the steps where the window is complete:

    lastwindow after shrinkingresult
    5ADOBECnew best, length 6
    6ADOBECOlonger than the best
    7ADOBECODlonger than the best
    8ADOBECODElonger than the best
    9ADOBECODEBlonger than the best
    10CODEBAsame length as the best
    11CODEBANlonger than the best
    12BANCnew best, length 4

    At last = 3, missing is 1: the window ADOB has an A and a B but no C. The window becomes complete at index 5, when the C arrives.

    Step by step

    1. Create need. Array.fill(128)(0) gives one counter per character code below 128. All letters, in both cases, have codes in that range, and each case gets its own counter.
    2. Count the characters of t. A for loop adds 1 to need(c.toInt) for each c. toInt gives the character's code, and a letter that appears twice in t is counted twice.
    3. Set missing to t.length. The empty window lacks every character of t.
    4. Declare first and bestStart, both 0. first is the window's left end and bestStart is where the best window begins.
    5. Set bestLength to s.length + 1. No window can be that long, so this value means that none has been found.
    6. Grow the window. for (last <- s.indices) adds the character at last in each turn. Its code goes into code.
    7. Update missing first. If need(code) is above 0, t still wanted this character, so missing goes down. Otherwise the character is an extra and missing stays.
    8. Then subtract 1 from need(code). This order matters: the test must see the counter before the character is counted.
    9. When missing == 0, shrink. A while loop runs while need(s(first).toInt) < 0, that is, while the first character is an extra. Each pass gives its copy back with need(s(first).toInt) += 1 and moves first right.
    10. Compare lengths. If last - first + 1 is less than bestLength, store the window's start and length.
    11. Return the result. If bestLength is still above s.length, no window was complete and the function returns "". Otherwise s.substring(bestStart, bestStart + bestLength) is the answer.

    The solution in Scala

    class Solution {
        def minWindow(s: String, t: String): String = {
            val need = Array.fill(128)(0)
            for (c <- t) {
                need(c.toInt) += 1
            }
            var missing = t.length
            var first = 0
            var bestStart = 0
            var bestLength = s.length + 1
            for (last <- s.indices) {
                val code = s(last).toInt
                if (need(code) > 0) missing -= 1
                need(code) -= 1
                if (missing == 0) {
                    while (need(s(first).toInt) < 0) {
                        need(s(first).toInt) += 1
                        first += 1
                    }
                    if (last - first + 1 < bestLength) {
                        bestStart = first
                        bestLength = last - first + 1
                    }
                }
            }
            if (bestLength > s.length) return ""
            s.substring(bestStart, bestStart + bestLength)
        }
    }
    

    The Scala details worth a closer look:

    • Char to Int. 'A'.toInt is 65 and 'z'.toInt is 122, so a 128-element array has a slot for every letter. Both c.toInt and s(last).toInt return a code point as an Int.
    • A one-line if. if (need(code) > 0) missing -= 1 has no braces and no else. As a statement it just runs the assignment when the condition holds.
    • Substring end is exclusive. s.substring(i, j) returns the characters at indexes i up to but not including j, so the end is bestStart + bestLength.
    • The early return. return "" leaves the method with a String. The last line has no return because the final expression of the block is the result.
    • Immutable strings. The window is only a pair of indexes. The substring is cut once, at the end, so no intermediate strings are built.

    Complexity

    Time: O(n + m). Counting the characters of t takes m steps. The loop over s runs n times, and the inner while loop moves first right by one on each pass and never moves it back, so over the whole call its body runs at most n times.

    Space: O(1). The counter array has 128 elements whatever the input. The only other storage is a few integers.

    Edge cases and common mistakes

    • No valid window. s = "abcdef" with t = "xyz" returns "", and so does s = "a" with t = "aa".
    • Repeated characters in t. With t = "aa", two copies are needed. s = "aab" with t = "aab" returns "aab", and s = "AAB" with t = "AA" returns "AA".
    • Case matters. s = "aAbB" with t = "Ab" returns "Ab": the lowercase a before it is a different character.
    • The order of characters doesn't matter. s = "abc" with t = "cba" returns "abc".
    • Counting an extra copy as progress. If missing dropped for every arriving character that appears in t, a window with three a's and no b could look complete when t is "ab". Testing need(code) > 0 before the decrement lets only the copies that t still wants count.
    • Swapping the two updates. Decrementing need(code) first makes the test need(code) > 0 miss the last needed copy.
    • Dropping a needed character. The shrink loop stops at a counter of 0, not below it: a counter at 0 means that the window holds exactly the copies t requires.
    • Returning on the first complete window. The first window found is rarely the shortest. The search continues to the end of s.

    Testing

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