☰ All problems

Longest Substring Without Repeating Characters

A typing tutor rewards variety: it looks for the longest stretch of a player's keystrokes in which no key is pressed twice. The keystrokes arrive as a string s, one character per key press, and letters, digits, symbols and the space bar all count as keys.

Return the length of the longest contiguous block of s whose characters are all different. An empty string gives 0.

Example 1
Input: s = "racecar"
Output: 4

Explanation: "race" (and also "ecar") has four different characters; every block of five repeats a letter.

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

Explanation: Spaces count as keys: "1 2" has three different characters, and extending it would repeat the space.

Example 3
Input: s = ""
Output: 0

Constraints

  • s is between 0 and 50,000 characters long.
  • s can contain 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