Minimum Window Substring
Problem statement
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.
Constraints:
m == s.lengthn == t.length1 <= m, n <= 105sandtconsist of uppercase and lowercase English letters.
O(m + n) time?My solution
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
if (!s || !t) {
return ""
}
let result = ""
let letterMap = new Map();
let left = 0;
let count = 0;
let minValue = Number.MAX_SAFE_INTEGER;
// Fill the Map
for (const char of t.split("")) {
if (!letterMap.has(char)) {
letterMap.set(char, 0)
}
letterMap.set(char, letterMap.get(char) + 1)
}
for (let right = 0; right < s.length; right++) {
const currChar = s.charAt(right);
if (letterMap.has(currChar) !== undefined) {
letterMap.set(currChar, letterMap.get(currChar) - 1);
if (letterMap.get(currChar) >= 0) {
count++
}
}
while (count === t.length) {
// console.log(">>> count", count, currChar)
if (minValue > right - left + 1) {
minValue = right - left + 1;
result = s.substring(left, right + 1);
}
if (letterMap.has(s.charAt(left)) !== undefined) {
letterMap.set(s.charAt(left), +letterMap.get(s.charAt(left)) + 1);
// console.log("<<<",s.charAt(left), letterMap.get(s.charAt(left)))
if (letterMap.get(s.charAt(left)) > 0) {
count--
}
}
left++
}
}
return result
};