Skip to content

Instantly share code, notes, and snippets.

@nidzovito
Last active December 2, 2022 02:48
Show Gist options
  • Save nidzovito/13ec02aeae8fb1a3411c2d1cf4c68d33 to your computer and use it in GitHub Desktop.
Save nidzovito/13ec02aeae8fb1a3411c2d1cf4c68d33 to your computer and use it in GitHub Desktop.
Algorithm to find the longest substring without repeating characters
// Given a string "input", find the length of the longest substring without repeating characters.
const lengthOfLongestSubstring = (input = "") => {
const chars = input.split("");
let buffer = new Map(); // stores the last index for each encountered character
let maxLen = 0;
for (let index = 0; index < chars.length; index++) {
const char = chars[index];
if (!buffer.has(char)) {
buffer.set(char, index);
} else {
index = buffer.get(char); // jump back to one after the last index of this character
buffer.clear();
}
maxLen = Math.max(maxLen, buffer.size);
}
return maxLen;
};
expect(lengthOfLongestSubstring('9098795672298')).toBe(5) // "87956"
expect(lengthOfLongestSubstring('pwwkew')).toBe(3) // "wke"
expect(lengthOfLongestSubstring('bbbbbb')).toBe(1) // "b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment