Overview
Given a string s, find the length of the longest substring without repeating characters.
Constraints
0 <= s.length <= 50,000sconsists of English letters, digits, symbols, and spaces.- Must run in O(n) time.
Examples
lengthOfLongestSubstring("abcabcbb");
// => 3 (substring: "abc")lengthOfLongestSubstring("bbbbb");
// => 1 (substring: "b")
lengthOfLongestSubstring("pwwkew");
// => 3 (substring: "wke")
lengthOfLongestSubstring("");
// => 0Solution
Reveal solution
function lengthOfLongestSubstring(s) {
const map = new Map();
let max = 0, left = 0;
for (let right = 0; right < s.length; right++) {
if (map.has(s[right]) && map.get(s[right]) >= left) {
left = map.get(s[right]) + 1;
}
map.set(s[right], right);
max = Math.max(max, right - left + 1);
}
return max;
}Sliding window with a map storing the last index of each character. When a duplicate is found, jump left past it.
Resources
longest-non-repeating-substring.js
Longest Non-repeating Substring
mediumcodingAlgorithmsSliding Window
Overview
Given a string s, find the length of the longest substring without repeating characters.
Constraints
0 <= s.length <= 50,000sconsists of English letters, digits, symbols, and spaces.- Must run in O(n) time.
Examples
lengthOfLongestSubstring("abcabcbb");
// => 3 (substring: "abc")lengthOfLongestSubstring("bbbbb");
// => 1 (substring: "b")
lengthOfLongestSubstring("pwwkew");
// => 3 (substring: "wke")
lengthOfLongestSubstring("");
// => 0Solution
Reveal solution
function lengthOfLongestSubstring(s) {
const map = new Map();
let max = 0, left = 0;
for (let right = 0; right < s.length; right++) {
if (map.has(s[right]) && map.get(s[right]) >= left) {
left = map.get(s[right]) + 1;
}
map.set(s[right], right);
max = Math.max(max, right - left + 1);
}
return max;
}Sliding window with a map storing the last index of each character. When a duplicate is found, jump left past it.
Resources
NameTopicDifficulty
103 of 103 problems