Problem
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
1 | |
Note:
- If there is no such window in S that covers all characters in T, return the empty string
"". - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
Explanation
-
Before we start, we need to get the frequency of the string
Tby using hashmap or an array. Then, we create amatchCountthat is used to count the number of matching characters in stringTthat are matched with the substring, and its maximum length will be the length ofT. We will also create aleftandrightthat points at the substring’s beginning and the end. We also need asArrto hold the substring’s mathing character frequency. -
First, we iterating the string
Sand find the first matching character and use theleftandrightpointers point at the first matching character, we also need to store its frequency tosArrand update thematchCountif necessary. Then, we find the next matching character, store its frequency and update thematchCountif necessary and we use therightpointer to point at it until we have the same number ofmatchCount. -
For example,
S = XXXAXXBAACXXX,T = AABC. Now,leftis pointing at the first A,rightis pointing at the C,matchCount=4=T.length(),tArr={A=2, B=1, C=1},sArr = {A=3, B=1, C=1}, and theresisAXXBAAC. Now, we move theleftpointer to point at the next match character which is B, the substring isBAAC. We removed one A fromsArr, it still has two A, in other word,sArr = {A=2, B=1, C=1}andmatchCountnot change, and we update theresbecause now the substring has shorter length than before. Now again, we move theleftpointer to point at the next match character which is A, the substring isAAC, andmatchCountchanged to 3, so we move therightpointer points to the next matching character and repeat this process until it hits the end.
Solution
1 | |