☰ All problems

18. Longest Substring Without Repeating Characters

Given a string s, return the length of the longest substring (a contiguous block of characters) in which no character appears more than once.

Example 1
Input: s = "abcdbef"
Output: 5

Explanation: "abcd" stops at the second b; starting just after the first b, "cdbef" has 5 distinct characters.

Example 2
Input: s = "aaaa"
Output: 1
Example 3
Input: s = ""
Output: 0

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces
💡 Hint 1

Keep a window [left, right] that never contains a repeated character, and grow it one character at a time.

💡 Hint 2

When the new character already occurs inside the window, the window must start just after that earlier occurrence.

💡 Hint 3

Remember the last index of every character so you can jump left directly instead of shrinking one step at a time. Never move left backwards.

/**
 * @param {string} s
 * @return {number}
 */
function lengthOfLongestSubstring(s) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc