Last active
June 27, 2021 23:06
-
-
Save CarlaTeo/0cdecd359f5202896553b7964e1f2b0e to your computer and use it in GitHub Desktop.
[JS] Minimum Length Substrings
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
// Solution |s|**2 + |t| | |
function containsSubstring(str, startIdx, endIdx, substrMap) { | |
const substrMapCopy = {...substrMap}; | |
for(let i = startIdx; i <= endIdx; i++) { | |
const char = str[i]; | |
if(substrMapCopy[char]) { | |
substrMapCopy[char] -= 1; | |
if(substrMapCopy[char] === 0) { | |
delete substrMapCopy[char]; | |
if(!Object.keys(substrMapCopy).length) return true; | |
} | |
} | |
}; | |
return false; | |
} | |
function minLengthSubstring(s, t) { | |
const mapT = {}; | |
t.split("").forEach(char => { | |
if(mapT[char]) mapT[char] += 1; | |
else mapT[char] = 1; | |
}); | |
let j = 0; | |
let minLengthSubstring = Infinity; | |
for(let i = 0; i < s.length; i++) { | |
while(j < s.length && !containsSubstring(s, i, j, mapT)) { | |
j++; | |
} | |
console.log(j) | |
if(j === s.length) break; | |
const newLength = j - i + 1; | |
if(newLength < minLengthSubstring) minLengthSubstring = newLength; | |
}; | |
return minLengthSubstring === Infinity ? -1 : minLengthSubstring; | |
} | |
// solution |s| + |t| | |
function minLengthSubstring(s, t) { | |
if(t.length > s.length) return -1; | |
if(t === "") return 0; | |
if(s === "") return -1; | |
const mapT = {}; | |
t.split("").forEach(char => { | |
if(mapT[char]) mapT[char] += 1; | |
else mapT[char] = 1; | |
}); | |
let result = Infinity; | |
let nOfFormed = 0; | |
let l = 0; | |
let r = 0; | |
while(r < s.length) { | |
if(mapT[s[r]] !== undefined) { | |
mapT[s[r]] -=1; | |
if(mapT[s[r]] === 0) nOfFormed++; | |
} | |
while(nOfFormed === t.length) { | |
const size = r - l + 1; | |
if(size < result) { | |
result = size; | |
if(result === t.length) return result; | |
} | |
if(mapT[s[l]] !== undefined) { | |
mapT[s[l]] += 1; | |
if(mapT[s[l]] >= 1) nOfFormed--; | |
} | |
l++; | |
} | |
r++; | |
} | |
return result === Infinity ? -1 : result; | |
} | |
// --------------------------- test -----------------------------// | |
console.log(minLengthSubstring("dcbefebce", "fd")) // 5 | |
console.log(minLengthSubstring("bfbeadbcbcbfeaaeefcddcccbbbfaaafdbebedddf", "cbccfafebccdccebdd")) // -1 | |
console.log(minLengthSubstring("", "fd")) // -1 | |
console.log(minLengthSubstring("dcbefebce", "")) // 0 | |
console.log(minLengthSubstring("dcffd", "fd")) // 2 | |
console.log(minLengthSubstring("dcffd", "fd")) // 2 | |
console.log(minLengthSubstring("dcffd", "az")) // -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment