Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sliding Window Find Longest Substring
findLongestSubstring Solution
function findLongestSubstring(str) {
let longest = 0;
let seen = {};
let start = 0;
for (let i = 0; i < str.length; i++) {
let char = str[i];
if (seen[char]) {
start = Math.max(start, seen[char]);
}
// index - beginning of substring + 1 (to include current in count)
longest = Math.max(longest, i - start + 1);
// store the index of the next char so as to not double count
seen[char] = i + 1;
}
return longest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment