Skip to content

Instantly share code, notes, and snippets.

@flacial
Created November 13, 2022 13:31
Show Gist options
  • Save flacial/44283acba514edd816e5fe8a488f0bc3 to your computer and use it in GitHub Desktop.
Save flacial/44283acba514edd816e5fe8a488f0bc3 to your computer and use it in GitHub Desktop.
Sliding Window: longest substring with distinct characters
const longestSubstringWithDistinctCharacters = str => {
let windowStart = 0;
let longestSubstring = 0;
const hashMap = {};
// Expand the window
for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
const rightChar = str[windowEnd];
// if the map already contains the 'rightChar', shrink the window from the beginning
// so that we have only one occurrence of 'rightChar'
if (rightChar in hashMap) {
windowStart = windowEnd;
} else {
// insert rightChar into the map
hashMap[rightChar] = windowEnd;
}
// remeber the max length so far
longestSubstring = Math.max(longestSubstring, windowEnd - windowStart + 1);
}
return longestSubstring;
};
longestSubstringWithDistinctCharacters('aabccbb');
longestSubstringWithDistinctCharacters('abbbb');
longestSubstringWithDistinctCharacters('abccde');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment