LeetCode #3 Medium

Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters is LeetCode 3 (Medium). Given a string s, return the length of the longest substring in which no character appears twice.

  • A substring is a contiguous run of s. Picking characters with gaps gives a subsequence, which does not count.
  • s has up to 50,000 characters: letters, digits, symbols and spaces. Checking every substring is far too slow.
Constraints
  • 0 <= s.length <= 5 * 10⁴
  • s consists of English letters, digits, symbols and spaces.
stringsliding-windowhash-table
Open on LeetCode ↗
02

Intuition

Keep a window with no repeats and push its right end forward. The window breaks only when the new character already has a copy inside it, and at that point every window that still contains the older copy is broken too. So the left end can jump straight past the older copy in one move, instead of crawling forward one step at a time.

To make the jump O(1), store the last index where each character appeared. The stored index is only worth acting on when it lies inside the current window.

How to spot this pattern

"Longest contiguous stretch with no duplicates" is a two-pointer window. When you can store where the offending item sits, move the left end straight past it instead of stepping.

03

Approach

Try it first

Before reading on: when a character repeats, which window starts can still be part of an answer? Then decide what you need to store to skip the rest at once. Aim for O(n).

1

Remember where each character was last seen

Keep last, a map from character to the latest index where it appeared, and left, where the current window starts. Read s once from left to right.

2

Jump past a repeat that is inside the window

If s[right] was last seen at an index >= left, set left to that index plus one. Every start at or before the older copy would hold both copies, so all of them are skipped in one move.

3

Record the character, then the length

Set last[s[right]] = right, then update best with right - left + 1. After the jump, the characters from left to right are all different, so this length is a real answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lengthOfLongestSubstring(self, s: str) -> int:
▶3 last = {}
▶4 left = best = 0
▶5 for right, ch in enumerate(s):
▶6 if last.get(ch, -1) >= left:
▶7 left = last[ch] + 1
▶8 last[ch] = right
▶9 best = max(best, right - left + 1)
▶10 return best
a0b1c2a3b4c5b6b7last seen ata–b–c–0bestno character seen yet
left0
best0
Each card will hold the last index where its character appeared. A dashed card means the character has not been read yet.
a0L Rb1c2a3b4c5b6b7last seen ata0b–c–1besta is new → length 1, best 1
left0
best1
a has not appeared before, so the window simply grows. Write 0 on the a card. The window from 0 to 0 is 1 long, a new best.
a0Lb1Rc2a3b4c5b6b7last seen ata0b1c–2bestb is new → length 2, best 2
left0
best2
b has not appeared before, so the window simply grows. Write 1 on the b card. The window from 0 to 1 is 2 long, a new best.
a0Lb1c2Ra3b4c5b6b7last seen ata0b1c23bestc is new → length 3, best 3
left0
best3
c has not appeared before, so the window simply grows. Write 2 on the c card. The window from 0 to 2 is 3 long, a new best.
a0b1Lc2a3Rb4c5b6b7left jumpslast seen ata0b1c23besta repeats at index 0 → left jumps to 1
left1
best3
a was last seen at index 0, which is inside the window (left is 0). A window starting at 0 would hold both copies, so the left end skips it and lands on 1, just past the older copy.
a0b1Lc2a3Rb4c5b6b7last seen ata3b1c23bestrecord a at 3 → length 3
left1
best3
With the older copy gone, the window holds each character once. Write 3 on the a card. The window from 1 to 3 is 3 long, not longer than the best 3.
a0b1c2La3b4Rc5b6b7left jumpslast seen ata3b1c23bestb repeats at index 1 → left jumps to 2
left2
best3
b was last seen at index 1, which is inside the window (left is 1). A window starting at 1 would hold both copies, so the left end skips it and lands on 2, just past the older copy.
a0b1c2La3b4Rc5b6b7last seen ata3b4c23bestrecord b at 4 → length 3
left2
best3
With the older copy gone, the window holds each character once. Write 4 on the b card. The window from 2 to 4 is 3 long, not longer than the best 3.
a0b1c2a3Lb4c5Rb6b7left jumpslast seen ata3b4c23bestc repeats at index 2 → left jumps to 3
left3
best3
c was last seen at index 2, which is inside the window (left is 2). A window starting at 2 would hold both copies, so the left end skips it and lands on 3, just past the older copy.
a0b1c2a3Lb4c5Rb6b7last seen ata3b4c53bestrecord c at 5 → length 3
left3
best3
With the older copy gone, the window holds each character once. Write 5 on the c card. The window from 3 to 5 is 3 long, not longer than the best 3.
a0b1c2a3b4c5Lb6Rb7left jumpslast seen ata3b4c53bestb repeats at index 4 → left jumps to 5
left5
best3
b was last seen at index 4, which is inside the window (left is 3). Every window starting anywhere from 3 to 4 would hold both copies, so the left end skips them all and lands on 5, just past the older copy.
a0b1c2a3b4c5Lb6Rb7last seen ata3b6c53bestrecord b at 6 → length 2
left5
best3
With the older copy gone, the window holds each character once. Write 6 on the b card. The window from 5 to 6 is 2 long, not longer than the best 3.
a0b1c2a3b4c5b6b7L Rleft jumpslast seen ata3b6c53bestb repeats at index 6 → left jumps to 7
left7
best3
b was last seen at index 6, which is inside the window (left is 5). Every window starting anywhere from 5 to 6 would hold both copies, so the left end skips them all and lands on 7, just past the older copy.
a0b1c2a3b4c5b6b7L Rlast seen ata3b7c53bestrecord b at 7 → length 1
left7
best3
With the older copy gone, the window holds each character once. Write 7 on the b card. The window from 7 to 7 is 1 long, not longer than the best 3.
a0b1c2a3b4c5b6b7last seen ata3b7c53bestanswer: 3
answer3
Every character was read once and left only moved forward. The longest window with no repeat is marked in green: 3 characters.
05

Set of the window, step

The set holds exactly the characters inside the window. When the next character is already in it, remove s[left] and step left until that copy is gone, then add the new one.

▶1class Solution:
▶2 def lengthOfLongestSubstring(self, s: str) -> int:
▶3 window = set()
▶4 left = best = 0
▶5 for ch in s:
▶6 while ch in window:
▶7 window.remove(s[left])
▶8 left += 1
▶9 window.add(ch)
▶10 best = max(best, len(window))
▶11 return best
06

Common pitfalls

Jumping back to an index outside the window

✗ Wrong
if ch in last:
    left = last[ch] + 1
✓ Right
if last.get(ch, -1) >= left:
    left = last[ch] + 1

last keeps characters that already left the window. On "abba", the final a was last seen at 0 while left is 2, so the wrong code pulls left back to 1, lets the two bs in again, and returns 3. The answer is 2.

Restarting the window at the repeat

✗ Wrong
if last.get(ch, -1) >= left:
    left = right
✓ Right
if last.get(ch, -1) >= left:
    left = last[ch] + 1

Characters between the older copy and right can stay. On "dvdf" the second d should keep "vd" and grow to "vdf" (3); restarting at the d gives "df" and returns 2.

07

Edge cases

Empty string

The loop never runs and best stays 0, which the constraints allow.

Spaces and symbols, e.g. "a b c"

A space is a character like any other, so the second space ends the window and the answer is 3 ("a b" or "b c"). The map does not care what kind of character it holds.

08

Complexity

Time
O(n)
Space
O(min(n, m))
Each character is read once and left only moves forward. m is the number of possible characters (at most 128 here), since last holds one entry per character, not per position.
09

Longest Substring Without Repeating Characters FAQ

How is this different from Longest Substring with At Most K Distinct Characters?

There a character may repeat freely and k caps how many different characters the window holds. Here every character may appear once, so the window needs no counts, only each character's last index.

Can an array replace the map?

Yes. The characters are ASCII, so an array of 128 ints filled with -1 does the same job: last[ord(ch)] instead of last.get(ch, -1). It avoids hashing and is often faster.