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
T
by using hashmap or an array. Then, we create amatchCount
that is used to count the number of matching characters in stringT
that are matched with the substring, and its maximum length will be the length ofT
. We will also create aleft
andright
that points at the substring’s beginning and the end. We also need asArr
to hold the substring’s mathing character frequency. -
First, we iterating the string
S
and find the first matching character and use theleft
andright
pointers point at the first matching character, we also need to store its frequency tosArr
and update thematchCount
if necessary. Then, we find the next matching character, store its frequency and update thematchCount
if necessary and we use theright
pointer to point at it until we have the same number ofmatchCount
. -
For example,
S = XXXAXXBAACXXX
,T = AABC
. Now,left
is pointing at the first A,right
is pointing at the C,matchCount=4=T.length()
,tArr={A=2, B=1, C=1}
,sArr = {A=3, B=1, C=1}
, and theres
isAXXBAAC
. Now, we move theleft
pointer 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}
andmatchCount
not change, and we update theres
because now the substring has shorter length than before. Now again, we move theleft
pointer to point at the next match character which is A, the substring isAAC
, andmatchCount
changed to 3, so we move theright
pointer points to the next matching character and repeat this process until it hits the end.
Solution
1 |
|