Created
November 13, 2022 13:31
-
-
Save flacial/44283acba514edd816e5fe8a488f0bc3 to your computer and use it in GitHub Desktop.
Sliding Window: longest substring with distinct characters
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
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