Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in Kotlin: 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

    KOTLIN · SLIDING WINDOW

    Minimum Window Substring in Kotlin, explained

    Problem overview

    minWindow receives two strings, s and t. 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, the function returns the empty string. Uppercase and lowercase letters are different characters.

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". For "a" and "a" it is "a". For "a" and "aa" it is "", because s has only one a.

    The statement asks for O(n + m) time and O(1) extra space, with n the length of s and m the length of t.

    Approach

    Checking every substring of s against t is far too slow. A sliding window does it in one pass. Move the right end of the window forward one character at a time until the window holds everything t needs. Then move the left end forward while the window stays complete, to make it as short as possible, and remember it if it is the shortest so far. Then the right end continues.

    To know whether the window is complete without recounting, the code keeps one array, need, indexed by character code. need[code] is how many more of that character the window still needs. A new character entering the window lowers its entry by one. A positive entry means the window is short of that character, zero means it has exactly enough, and a negative entry means it holds spare copies. A second number, missing, counts how many characters of t the window still lacks, so the window is complete exactly when missing is 0.

    Step by step

    1. Create need, an IntArray(128). Letters have codes below 128, so one entry per code covers a to z and A to Z, each case separately.
    2. Count the characters of t. Looping for (c in t) and adding 1 to need[c.code] records how many copies of each letter the window must hold. c.code is the character's code as an Int.
    3. Set missing to t.length. Before the window holds anything, it lacks every character of t.
    4. Create first, bestStart and bestLength. first is the left end of the window. bestLength starts at s.length + 1, a value no real window can have, which means no complete window has been found yet.
    5. Loop last over s.indices, adding the character at last to the window. Read its code into code.
    6. Update the counts. If need[code] is above 0, the window really needed this character, so missing goes down. If it is 0 or negative, the character is an extra copy and missing stays. In both cases need[code] then goes down by one.
    7. When missing == 0, the window is complete. Move first right while need[s[first].code] < 0: a negative entry means the window has more of that character than t asks for, so dropping the character keeps the window complete. Each drop adds 1 back to its entry.
    8. Compare lengths. If last - first + 1 is smaller than bestLength, remember first and the new length. Only the start and the length are stored, so the substring is cut once, at the end.
    9. After the loop, if bestLength is still above s.length, no window was ever complete, so return "". Otherwise return the substring from bestStart up to bestStart + bestLength.

    The solution in Kotlin

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

    Some Kotlin details in this code:

    • c.code turns a Char into its numeric code. For example 'a'.code is 97 and 'A'.code is 65.
    • if (need[code] > 0) missing-- is a one-line if without braces. Kotlin allows that for a single statement.
    • substring(i, j) includes index i and excludes index j, hence bestStart + bestLength as the end.
    • need[code]-- works on an array element directly. A new IntArray is filled with zeros.

    Tracing the example

    This is the state after each character of s = "ADOBECODEBANC" with t = "ABC":

    last=0 A missing=2 first=0 best=none
    last=1 D missing=2 first=0 best=none
    last=2 O missing=2 first=0 best=none
    last=3 B missing=1 first=0 best=none
    last=4 E missing=1 first=0 best=none
    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
    

    The window first becomes complete at index 5 (ADOBEC). At index 10 the second A arrives, which lets the left end jump from 0 to 5, giving CODEBA, no shorter than the best. At index 12 the last C arrives and the left end moves to 9, giving BANC with length 4.

    Complexity

    Time: O(n + m). Counting t takes m steps. After that last visits each index of s once, and first only moves right, so the inner while runs at most n times in total.

    Space: O(1). The need array has 128 entries whatever the input.

    Edge cases and common mistakes

    • Repeated characters in t. "aab" with t = "aab" returns "aab": the count in need is 2 for a, so a window with one a is not complete.
    • No valid window. "a" with t = "aa" returns "".
    • Case matters. "Ab" with t = "ab" returns "", because A and a have different codes.
    • Extra copies. In "abcabc" with t = "cba" the answer is "abc", the first window that is complete. Later windows of the same length don't replace it, because the comparison is strict (<).
    • Counting only distinct characters. Using a set instead of counts would accept a window with one a when t needs two.
    • Using the window length as the answer. The function returns the substring, not its length, and uses "" when nothing was found.

    Testing

    "ADOBECODEBANC" "ABC" -> "BANC"
    "a" "a" -> "a"
    "a" "aa" -> ""
    "aab" "aab" -> "aab"
    "abcabc" "cba" -> "abc"
    "Ab" "ab" -> ""
    "aaflslflsldkalskaaa" "aaa" -> "aaa"
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free