Skip to main content

Longest Substring Without Repeating Characters

MediumStringsSliding windowHash map323 tests

Given a string s, find the length of the longest substring that contains no repeated characters.

A substring is a contiguous run of characters — "abc" is a substring of "abcd", but "acd" is not.

Example 1

text

The answer is "abc", with length 3.

Example 2

text

The answer is "b".

Example 3

text

The answer is "wke". Note that "pwke" is a subsequence, not a substring.

Checking every substring is O(n²) or worse. A window that only ever moves forward gets it in O(n).

Examples

Example 1

Input:
"abcabcbb"
Output:
3

The longest run without a repeat is "abc".

Example 2

Input:
"bbbbb"
Output:
1

Every character is the same, so the window can never grow past one.

Example 3

Input:
"pwwkew"
Output:
3

The answer is "wke". "pwke" is a subsequence, not a substring.

Constraints

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

Run checks your code against the 3 examples. Submit checks it against all 323 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.