Created
August 6, 2021 09:06
-
-
Save gauravkr0071/49f071b278389082c68c9bb66a8cc5de to your computer and use it in GitHub Desktop.
Minimum window substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*/ | |
Minimum Window Substring | |
Hard | |
7469 | |
471 | |
Add to List | |
Share | |
Given two strings s and t of lengths m and n respectively, return the minimum window substring of 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. | |
A substring is a contiguous sequence of characters within the string. | |
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. | |
*/ | |
string minWindow(string s, string t) { | |
vector<int> map(128,0); | |
for(auto c: t) map[c]++; | |
int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0; | |
while(end<s.size()){ | |
if(map[s[end++]]-->0) counter--; //in t | |
while(counter==0){ //valid | |
if(end-begin<d) d=end-(head=begin); | |
if(map[s[begin++]]++==0) counter++; //make it invalid | |
} | |
} | |
return d==INT_MAX? "":s.substr(head, d); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment