Skip to main content

Longest Substring Without Repeating Characters

Problem

Given a string s, find the length of the longest substring without repeating characters.

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Solution

/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let l = 0; // left of window
let r = 0; // right of window
let max = 0; // longest substring without repeating characters
const map = {}; // index of last character occurrence in s[l:r + 1]

for (; r < s.length; r++) {
const c = s[r];
if (c in map) {
l = Math.max(map[c] + 1, l);
}
map[c] = r;
max = Math.max(max, r - l + 1);
}
return max;
};

We will implement a sliding window solution. If the current character c is in map, and l is less than map[c], this means c is a repeated character in the current substring (ie. c has appeared twice in s[l:r + 1]). Thus, set l to map[c] + 1 (ie. the character directly after the first occurrence of c) ensures s[l:r + 1] again has no repeated characters. Finally, update map, r, and max as needed.