Skip to content

Instantly share code, notes, and snippets.

@shuboy2014
Created March 10, 2020 14:53
Show Gist options
  • Save shuboy2014/2d74292e5b212b24eddeb5d51fb64571 to your computer and use it in GitHub Desktop.
Save shuboy2014/2d74292e5b212b24eddeb5d51fb64571 to your computer and use it in GitHub Desktop.
Interviewbit Window String
module.exports = {
minWindow : function(A, B){
const map = {};
let missing = B.length;
let fast=0, slow=0;
let shortest = [0,Infinity];
for(let i=0;i<B.length;i++){
if(B[i] in map){
map[B[i]].cnt += 1;
}else{
map[B[i]] = {
cnt: 1,
value: 0
};
}
}
for(fast=0;fast<A.length;fast++){
if(A[fast] in map){
if(map[A[fast]].value < map[A[fast]].cnt){
missing -= 1;
}
map[A[fast]].value += 1;
}
while(missing == 0){
if( (fast - slow) < (shortest[1] - shortest[0])){
shortest[0] = slow;
shortest[1] = fast;
}
if(A[slow] in map){
map[A[slow]].value -=1;
if(map[A[slow]].value < map[A[slow]].cnt){
missing+=1;
}
}
slow++;
}
}
return shortest[1] === Infinity ? "" : A.slice(shortest[0], shortest[1] + 1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment