Minimum Window Substring

Question (LC.76)

Given a string S and a string T, find the minimum window in S which will contain all the characters in T.

If there is no such window in S that covers all characters in T, return the empty string "".

Example

I: S = "ADOBECODEBANC", T = "ABC"
O: "BANC"

Order doesn't matter as long as the window contains all the information.

Analysis

We need a hash map to store all characters in T and their frequency. Then scan through S to find the minimum window that contains all the characters.

Brute Force Approach

for i from 0 to len(S)
    for j from i to len(S)
        if (currentChars includes searchChars)
            break
        else
            update currentChars
            j++
    end for
    update min substring j-i+1
end for

Sliding Window Approach

Code

Time & Space Complexity

Time O(n*#chars + m) Space O(n) can be optimized to O(m) by using a counter instead of calling isContained function with two maps

Last updated