Skip to content

Commit

Permalink
5. Minimum Window Substring
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunjae95 committed Oct 6, 2024
1 parent e773cf0 commit 8621430
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions minimum-window-substring/sunjae.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @description
* brainstorming:
* two pointer + hash table
*
* n = length of s
* m = length of t
* time complexity: O(n*n)
* space complexity: O(n)
*/
var minWindow = function (s, t) {
const requiredMap = t.split("").reduce((map, char) => {
map.set(char, (map.get(char) ?? 0) + 1);
return map;
}, new Map());
const requiredArray = [...requiredMap.entries()];
const map = new Map();
const successRequired = () =>
requiredArray.every(([key, value]) => map.get(key) >= value);

let answer = "";
let start = 0;

for (let i = 0; i < s.length; i++) {
if (requiredMap.has(s[i])) map.set(s[i], (map.get(s[i]) ?? 0) + 1);

while (successRequired()) {
const now = s.slice(start, i + 1);
answer = answer === "" || answer.length >= now.length ? now : answer;

if (map.has(s[start])) {
map.set(s[start], map.get(s[start]) - 1);
if (map.get(s[start]) === -1) map.delete(s[start]);
}

start++;
}
}

return answer;
};

0 comments on commit 8621430

Please sign in to comment.