You are given a string s. Write a function to find the longest substring that contains no repeated characters. Please this is a classic sliding window problem, write a function that solves this problem, and explain your algorithm.
Assistant
We are going to solve the longest substring without repeating characters problem using a sliding window approach.
Steps:
We'll use two pointers, left and right, to represent the current window.
We'll maintain a set (or a dictionary) to keep track of the characters in the current window.
We'll move the right pointer to expand the window until we find a duplicate.
When a duplicate is found, we move the left pointer to the right until the duplicate is removed from the window.
At each step, we update the maximum length of the substring without repeating characters.
Alternatively, we can use a dictionary to store the last index of each character. This way, when we find a duplicate, we can jump the left pointer to the position after the last occurrence of the duplicated character (if it's within the current window).
Let's implement the second method because it is more efficient (each character is visited at most twice).
Algorithm with dictionary (last index of characters):
Let left = 0, max_len = 0.
Create an empty dictionary to store the last index of each character.
For right in range(len(s)):
If s[right] is in the dictionary and its last index is >= left, then we have a duplicate in the current window.
So, we move left to last_index[s[right]] + 1.
Update last_index[s[right]] = right.
Then update max_len = max(max_len, right - left + 1)
However, note that we only update left when the duplicate character's last index is within the current window (i.e., >= left). Otherwise, we can just update the last index and continue.
Example:
s = "abcabcbb"
left=0, right=0: 'a' -> last_index: {'a':0}, max_len=1
right=1: 'b' -> not in current window? Actually, check: if 'b' in last_index? No. So update last_index['b']=1, max_len=2.
right=2: 'c' -> same, update, max_len=3.
right=3: 'a' -> last_index['a']=0, which is >= left (0) -> duplicate. So left = 0+1 = 1.
Then update last_index['a']=3, now window is [1,3] -> "bca", length=3.
right=4: 'b' -> last_index['b']=1, which is >= left (1) -> duplicate. So left = 1+1=2.
Then update last_index['b']=4, window [2,4] -> "cab", length=3.
right=5: 'c' -> last_index['c']=2, >= left (2) -> duplicate. left = 2+1=3.
update last_index['c']=5, window [3,5] -> "abc", length=3.
right=6: 'b' -> last_index['b']=4, which is >= left (3) -> duplicate. left = 4+1=5.
update last_index['b']=6, window [5,6] -> "cb", length=2.
right=7: 'b' -> last_index['b']=6, which is >= left (5) -> duplicate. left = 6+1=7.
update last_index['b']=7, window [7,7] -> "b", length=1.
So max_len remains 3.
But wait, the example above has max_len=3? Actually, the answer for "abcabcbb" is 3 ("abc" or "bca" or "cab").
However, note that in the example, at right=3 we had window [1,3] which is "bca", length=3. Then at right=4 we have "cab", also length=3. So we keep max_len=3.
But what about "dvdf"?
s = "dvdf"
left=0, right=0: 'd' -> last_index{'d':0}, max_len=1.
right=1: 'v' -> not in? Actually, not in the current window? last_index.get('v') is None -> so update, max_len=2.
right=2: 'd' -> last_index['d']=0, but left=0 so duplicate? Yes, because 0>=0. So left = 0+1=1.
Then update last_index['d']=2, window [1,2] -> "vd", length=2.
right=3: 'f' -> not in? update, window [1,3] -> "vdf", length=3.
So max_len=3.
But note: the substring "vdf" is indeed without duplicates.
However, the example "abba":
s = "abba"
left=0, right=0: 'a' -> last_index{'a':0}, max_len=1.
right=1: 'b' -> not in, update, max_len=2.
right=2: 'b' -> last_index['b']=1, which is >= left (0) -> duplicate. So left = 1+1=2.
update last_index['b']=2, window [2,2] -> "b", length=1.
right=3: 'a' -> last_index['a']=0, but now left=2. Is 0 >= 2? No. So we don't move left?
Then update last_index['a']=3, window [2,3] -> "ba", length=2.
So max_len=2.
But note: when we see the second 'a' at index 3, the current window is [2,3] which is "ba". The last index of 'a' was 0, which is not in the current window (because left=2). So we don't move left. That's correct.
Implementation:
Let's code accordingly.
Steps in code:
left = 0
max_len = 0
last_index = {} # dictionary for character -> last index
for right, char in enumerate(s):
if char in last_index and last_index[char] >= left:
left = last_index[char] + 1
last_index[char] = right
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
return max_len
However, note that we are only updating max_len at every step? Yes.
But what about when we move left? We then have a new window and we compute the current length.
But wait, in the example "abba", at right=3 we have:
left=2, right=3 -> current_len=2, which is not greater than max_len (which was 2 from [0,1]? Actually, max_len was 2 from [0,1] and then at right=2 we had 1, so max_len remains 2. Then at right=3 we have 2 again, so no update.
But what if we have a longer substring that starts at a later position? We are always taking the current window's length.
This algorithm works because we are expanding the right and adjusting left to the minimum possible to avoid duplicates, and then we check the length.
However, note that the condition for moving left: we only move left if the duplicate character's last index is within the current window (>= left). Otherwise, we don't move left because the duplicate is not in the current window.
But what if we have multiple duplicates? We only care about the current character's duplicate.
Let's test with "tmmzuxt":
Expected answer: 5 (for "mzuxt"? Actually, let's see:
t -> 1
tm -> 2
tmm -> duplicate, so left becomes index of first m +1 = 2? Actually, first m at index1, so left=2? Then window "m", then next 'z' -> "mz", then 'u' -> "mzu", then 'x' -> "mzux", then 't' -> "mzuxt" (5). But note that the second 't' at the end: we have already seen 't' at index0, but left=2 so 0<2, so we don't move left? Then we get "mzuxt" which is 5. But wait, what about the substring "tmmzuxt"? That has two m's. So we break at the second m.
Let's run step by step:
s = "tmmzuxt"
left=0, max_len=0
r0: 't' -> not in? last_index{'t':0}, max_len=1.
r1: 'm' -> not in? update, max_len=2.
r2: 'm' -> in last_index and last_index['m']=1 >= left=0 -> duplicate. left = 1+1=2.
update last_index['m']=2, current window [2,2] -> "m", length=1 -> max_len=2.
r3: 'z' -> not in? update, window [2,3] -> "mz", length=2.
r4: 'u' -> not in? update, window [2,4] -> "mzu", length=3.
r5: 'x' -> not in? update, window [2,5] -> "mzux", length=4.
r6: 't' -> in last_index? yes, last_index['t']=0, but left=2, so 0<2 -> not in current window. So we don't move left.
update last_index['t']=6, window [2,6] -> "mzuxt", length=5 -> max_len=5.
So answer=5, which is correct.
But note: the example "abba" we did earlier also works.
However, there is a catch: what if the string is empty? We should return 0.
Let's code accordingly.
But wait, what if we have a string like "aab"?
s = "aab"
left=0, max_len=0
r0: 'a' -> not in? update, max_len=1.
r1: 'a' -> in last_index and last_index['a']=0 >= left=0 -> duplicate. left = 0+1=1.
update last_index['a']=1, current window [1,1] -> "a", length=1.
r2: 'b' -> not in? update, window [1,2] -> "ab", length=2 -> max_len=2.
So answer=2, which is correct.
So the algorithm seems solid.
However, note that we are only updating the last index of the current character. And when we see a duplicate that is in the current window, we jump left to one after the last occurrence of that character.
But what if there are multiple duplicates? For example, "abac":
s = "abac"
left=0, max_len=0
r0: 'a' -> update, max_len=1.
r1: 'b' -> update, max_len=2.
r2: 'a' -> duplicate, last_index['a']=0 >= left=0 -> left=1.
update last_index['a']=2, window [1,2] -> "ba", length=2.
r3: 'c' -> not in, update, window [1,3] -> "bac", length=3 -> max_len=3.
Correct.
Implementation:
We'll write a function lengthOfLongestSubstring that takes a string s and returns an integer.
Let's code:
We'll solve this classic sliding window problem efficiently using a hash map to track character positions, achieving O(n) time and O(min(n, m)) space (where m is the character set size).
Algorithm Explanation
Core Idea
Maintain a window[left, right] that always contains no duplicate characters. Expand right to include new characters. When a duplicate s[right] appears, shrink the window from the left until the duplicate is removed.
Key Data Structure
Use a dictionary (hash map)char_index to store the most recent index of each character seen. This lets us instantly:
Check if s[right] is already in the current window.
Jump left directly past the previous occurrence (avoiding step-by-step shrinking).
Step-by-Step Process
Initialize:
left = 0 (start of window)
max_len = 0 (result)
char_index = {} (stores char -> last index)
Iterate right from 0 to len(s)-1:
If s[right] is in char_indexand its stored index >= left:
Duplicate inside window → move left to char_index[s[right]] + 1 (just past the previous occurrence).
Update char_index[s[right]] = right (track latest position).
Update max_len = max(max_len, right - left + 1).
Return max_len.
Code Implementation
python
def length_of_longest_substring(s: str) -> int:
"""
Returns the length of the longest substring without repeating characters.
Uses sliding window with hash map for O(n) time.
"""
if not s:
return 0
char_index = {} # char -> last seen index
left = 0
max_len = 0
for right, char in enumerate(s):
# If char is in current window, shrink window from left
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
# Update latest position of char
char_index[char] = right
# Update max length
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
return max_len
Example Walkthrough
Input:s = "abcabcbb"
right
char
char_index (before update)
left (before)
Action
left (after)
window [left, right]
current_len
max_len
0
'a'
{}
0
'a' new → no move
0
[0,0] "a"
1
1
1
'b'
{'a':0}
0
'b' new → no move
0
[0,1] "ab"
2
2
2
'c'
{'a':0,'b':1}
0
'c' new → no move
0
[0,2] "abc"
3
3
3
'a'
{'a':0,'b':1,'c':2}
0
'a' duplicate at index 0 ≥ left → left=0+1=1
1
[1,3] "bca"
3
3
4
'b'
{'a':3,'b':1,'c':2}
1
'b' duplicate at index 1 ≥ left → left=1+1=2
2
[2,4] "cab"
3
3
5
'c'
{'a':3,'b':4,'c':2}
2
'c' duplicate at index 2 ≥ left → left=2+1=3
3
[3,5] "abc"
3
3
6
'b'
{'a':3,'b':4,'c':5}
3
'b' duplicate at index 4 ≥ left → left=4+1=5
5
[5,6] "cb"
2
3
7
'b'
{'a':3,'b':6,'c':5}
5
'b' duplicate at index 6 ≥ left → left=6+1=7
7
[7,7] "b"
1
3
Result:3
Why This Works
left only moves forward: Once a character is excluded from the window, it never returns (guarantees O(n) time).
Direct jumps: When a duplicate appears, left jumps to last_occurrence + 1 instead of moving one-by-one.
Constant-time checks: Dictionary lookups are O(1) average case.
Complexity Analysis
Time:O(n) — Each character is processed exactly once (both left and right traverse at most n steps).
Space:O(min(n, m)) — Dictionary stores at most one entry per unique character in the current window (bounded by character set size m, e.g., 128 for ASCII).
Edge Cases Handled
Empty string → returns 0.
All unique → entire string length.
All same → returns 1 (e.g., "aaaa" → "a").
Duplicate not in window → left doesn’t move (e.g., "abba" at last 'a' → left stays at 2).
This implementation is optimal and widely used in production code. You can test it with: