3/670

3. Longest Substring Without Repeating Characters

Medium

You are given a single string s. Return the length of the longest contiguous substring of s in which no character repeats.

A substring is a run of consecutive characters (order preserved, no gaps). Among all such runs whose characters are all distinct, report the size of the largest one, an integer. The input s may be empty (answer 0), and it can contain spaces, digits, letters, or symbols, every distinct character counts, including the space character.

Example 1:

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is `abc`, with length 3. Any longer window would repeat a character (e.g. `abca` repeats `a`).

Example 2:

Input: s = "bbbbb"

Output: 1

Explanation: Every character is `b`, so the longest run of distinct characters is a single `b`, length 1.

Example 3:

Input: s = "pwwkew"

Output: 3

Explanation: The answer is `wke`, length 3. Note `pwke` is a *subsequence*, not a substring, so it does not count.

Constraints:

  • 0 ≤ s.length ≤ 5 * 10⁴
  • s consists of English letters, digits, symbols, and spaces.

Hints:

Brute force checks every substring and asks 'are all its characters distinct?', that is O(n^2) substrings times O(n) to check.

Keep a window that always has distinct characters. When a repeat appears, move the left edge just past the previous occurrence.

Store each character's last index so you can jump the left edge in one step instead of removing characters one at a time, but only jump when that index is inside the current window.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "abcabcbb"

Expected output: 3