Longest Substring Without Repeating Characters

35 min · lengthOfLongestSubstring()

A repeated character can erase a promising streak in one step. Your job is to keep the longest streak alive.

Given a string s, return the length of its longest substring — a contiguous stretch of characters — in which every character is different. The substring may contain letters, digits, spaces, or symbols. If s is empty, return 0.

A few ground rules:

  • Character comparisons are exact: A and a are different.
  • Spaces count as characters, just like letters and punctuation.
  • You return only the length, not the substring itself.

Constraints

  • 0 <= s.length <= 100_000
  • s consists of printable ASCII: the basic letters, digits, symbols, and space.

Hints

Start from every position

Fix a starting position and extend right until the next character is already in your set. That gives the best duplicate-free substring for that start. What work gets repeated when you move the start one step?

Keep one movable window

Track a window whose characters are all different. When the new rightmost character repeats, move the left edge past its previous copy.

Remember the last position

Store character → latest index. A repeat may sit outside the current window, so move left forward only when that saved index is at least left.

Follow-up

Could you return the substring as well without changing the O(n) running time?

Visible cases

Examples

Example 1

ready
Input
s = "abcabcbb"
Expected
3
Why
'abc' is the longest stretch with no repeated character

Example 2

ready
Input
s = "bbbbb"
Expected
1
Why
every duplicate-free stretch contains just one 'b'

Example 3

ready
Input
s = "pwwkew"
Expected
3
Why
'wke' has length 3; the answer must be contiguous

Interview signal

Asked at

AmazonGoogleBloombergAdobe
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite