Sliding window problem with 2 pointer
Given two strings s
and t
of lengths m
and n
respectively, return the minimum window
s
such that every character in t
(including duplicates) is included in the window. If there is no such substring, return the empty string ""
.
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.length
n == t.length
1 <= m, n <= 105
s
andt
consist of uppercase and lowercase English letters.
Solution:
For this question we are going to use sliding window approach. Firstly create an array of 128 length which will act as frequency array for the String, now in bigger string increment right counter until we have all the characters needed (usefull characters count will be 0 in map) we can have useless characters as well we don't care about them for now. Mind it, as we are decreasing count of usefull characters from map, reduce count of useful characters count. we stop decreasing this counter as soon as for a given "useful character" we have enough of them. like if we need 2 'a' we don't reduce useful character count no matter how many more a we get, but we still update map array and it will go negative.
As soon as we have all useful characters we store this ans and, we start checking left pointer and start increasing it (we do it till count is 0 meaning we still have all useful characters after left pointer is incremented), we increment values in map as well. When right pointer is at the position where we have all useful characters the usefull character map values should be 0 and for non usefull characters it can be 0 or -ve.
As we increment left pointer we update (increment) map. so when while updating map if we have 0 for any value we know it is a useful character hence we increase count as well meaning we need the useful character and we stop increasing left one. We go back on increasing right pointer unless we have this needed character that we lost. we run this until right pointer reaches end and count is still 0.
Usefull tips: use 128 array to use as character frequency, use frequency value sign (-ve or +ve) to determine if we have enough of usefull character and build logic.
Comments
Post a Comment