Longest Substring Without Repeating Characters

MediumSliding window

Given a string s, return the length of its longest substring, a run of consecutive characters, in which no character appears twice.

Examples

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

xyz, yzx and zxy are the longest runs without a repeat.

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

Any run longer than one character repeats the a.

Constraints

  • 0 ≤ s.length ≤ 5 × 10⁴
  • s can hold letters, digits, symbols and spaces.

Stuck?

Hint 1

Keep a window of characters with no repeat, and extend it to the right one character at a time.

Hint 2

When the new character is already in the window, move the left edge just past its last position. A Map of last positions makes that a jump instead of a walk.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur