Longest Substring Without Repeating Characters

medium

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

A substring is a contiguous run of characters within the string.

Hints

Keep a window of characters with no repeats; how do you react when a repeat enters?
Extend the right edge each step; on a duplicate, move the left edge forward.
Shrink from the left only until the repeated character is removed, then record the length.

Common doubts

The left pointer only moves forward and never past the right pointer, so across the whole run it advances at most n times total — the inner loop is amortized O(1).
Keep shrinking until the specific repeated character leaves the window — usually a few steps, exactly enough to restore uniqueness.
Yes — storing each character's last index lets you jump left directly past the previous occurrence, a common O(n) variant.

Interview follow-ups

Track the (left, right) pair whenever you update the best length, then slice the string at the end.
Swap the validity check: keep counts and shrink while any character's count exceeds the allowed repeats — the same template with a different invalid condition.

Fun facts

  • This is the archetypal variable-size sliding window — nearly every 'longest substring with property X' problem is this template with a different validity test.
  • The last-seen-index variant is a favorite because it turns the inner while-loop into a single pointer jump.

Asked at

AmazonGoogleMicrosoftMetaBloomberg
Frequently Sometimes Occasionally
Example 1
Input: s = "abcabcbb"
Output: 3
The longest substring without repeats is "abc", of length 3.
Example 2
Input: s = "bbbbb"
Output: 1
The best is "b", of length 1.
Constraints

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

Solve this problem →