We'll proceed with the above logic until we get all the required letters that we needed, which is directed by while counter == 0:
. Once we find the substring containing all the letters we need, we can then proceed since we've found a valid condition.
We're now sure that we've covered all the letters we need, but our window may be bigger than we need it to be. We can then shrink our window until we do not have a valid substring. Here's the code block for when we find a letter in the substring that isn't necessary.
xxxxxxxxxx
23
// from here, we increase begin pointer to make it invalid/valid again
while (counter === 0) { // valid, we have what we need
// calculate the current substring size since we care about min
if (end - begin + 1 < substrSize) { // overwrite if current substr is smaller
substrSize = end - begin + 1;
head = begin;
}
// we want to shrink it from the beginning now
// to make it the minimum size possible
if (s[begin] in hash) {
hash[s[begin]] += 1
// this is a character we need
if (hash[s[begin]] > 0) {
counter += 1; // make it invalid
}
}
begin += 1;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment