We are going to solve the problem using the sliding window technique.
Steps:
- We'll use a set (or a dictionary) to keep track of the characters in the current window.
- We'll have two pointers, left and right, to represent the current window.
- We'll move the right pointer to the right and add the character at right to the set.
- If we encounter a character that is already in the set (i.e., duplicate), we move the left pointer to the right until the duplicate is removed from the set.
- We keep track of the maximum length of the window (which has all unique characters) and update it when we find a longer one.
- We also keep track of the starting index of the longest substring so we can return the substring itself.
Alternatively, we can use a dictionary to store the last index of each character, so that when we find a duplicate, we can jump the left pointer to the position right after the last occurrence of that duplicate character.
However, note: if we use a set and just move left one by one, it's also O(n) because each character is visited at most twice.
Let me write the algorithm:
Initialize:
left = 0
max_length = 0
start_index = 0 (to record the start of the longest substring)
char_set = set()
For right in range(len(s)):
while s[right] in char_set:
remove s[left] from char_set
left += 1
add s[right] to char_set
current_length = right - left + 1
if current_length > max_length:
max_length = current_length
start_index = left
Then return s[start_index:start_index+max_length]
But note: the above while loop may run multiple times, but overall each character is added and removed at most once, so O(n).
However, we can optimize by using a dictionary to store the index of each character, and then when we see a duplicate, we can set left to max(left, last_occurrence[char] + 1). This avoids the while loop.
Let me do the dictionary version:
left = 0
max_length = 0
start_index = 0
last_occurrence = {}
for right in range(len(s)):
if s[right] in last_occurrence and last_occurrence[s[right]] >= left:
left = last_occurrence[s[right]] + 1
last_occurrence[s[right]] = right
current_length = right - left + 1
if current_length > max_length:
max_length = current_length
start_index = left
return s[start_index:start_index+max_length]
But note: the condition last_occurrence[s[right]] >= left is important because we only care about duplicates in the current window.
Let's test with "abcabcbb":
Initially: left=0, max_length=0, start_index=0, last_occurrence={}
right=0: s[0]='a', not in last_occurrence -> last_occurrence={'a':0}, current_length=1, max_length=1, start_index=0.
right=1: s[1]='b', not in -> last_occurrence={'a':0, 'b':1}, current_length=2, max_length=2, start_index=0.
right=2: s[2]='c', not in -> last_occurrence={'a':0, 'b':1, 'c':2}, current_length=3, max_length=3, start_index=0.
right=3: s[3]='a', in last_occurrence and last_occurrence['a']=0 >= left(0) -> left = 0+1 = 1.
update last_occurrence['a']=3, current_length=3 (3-1+1=3), max_length=3, start_index=0.
right=4: s[4]='b', in and last_occurrence['b']=1 >= left(1) -> left=1+1=2.
update last_occurrence['b']=4, current_length=4-2+1=3, max_length=3.
right=5: s[5]='c', in and last_occurrence['c']=2 >= left(2) -> left=2+1=3.
update last_occurrence['c']=5, current_length=5-3+1=3.
right=6: s[6]='b', in and last_occurrence['b']=4 >= left(3) -> left=4+1=5.
update last_occurrence['b']=6, current_length=6-5+1=2.
right=7: s[7]='b', in and last_occurrence['b']=6 >= left(5) -> left=6+1=7.
update last_occurrence['b']=7, current_length=7-7+1=1.
So the longest is 3, which is correct.
But wait, what about "abba"? Let's test:
left=0, max_length=0, start_index=0, last_occurrence={}
right=0: 'a' -> last_occurrence={'a':0}, current_length=1, max_length=1, start_index=0.
right=1: 'b' -> last_occurrence={'a':0, 'b':1}, current_length=2, max_length=2, start_index=0.
right=2: 'b' -> in and last_occurrence['b']=1 >= left(0) -> left=1+1=2.
update last_occurrence['b']=2, current_length=2-2+1=1, max_length=2.
right=3: 'a' -> in and last_occurrence['a']=0, but 0 < left(2) -> so we don't update left?
Actually, we must check: if the last occurrence of 'a' is before left, then it's not in the current window, so we don't move left.
So condition: if s[right] in last_occurrence and last_occurrence[s[right]] >= left -> then we move left.
Here, last_occurrence['a']=0 < left(2) -> so we don't move left.
Then update last_occurrence['a']=3, current_length=3-2+1=2, max_length=2.
So the longest is 2, which is correct (the substring "ab" or "ba"? Actually "ab" at [0:2] and then "ba" at [2:4] but note that at right=3, the window is [2:4] which is "ba", but then we don't update max_length because 2 is not greater than 2.
However, note that when we are at right=3, the window is [2,3] which is "ba", and that's of length 2. So it's correct.
But wait, what about the substring "ab" at [0:2]? We recorded that as max_length=2 and start_index=0. Then at the end we return s[0:2] which is "ab". That's fine.
But note: in the condition for moving left, we must ensure that we only move left when the duplicate is in the current window. So the condition last_occurrence[s[right]] >= left is correct.
However, there is a subtlety: when we update left, we set it to last_occurrence[s[right]] + 1. But what if the last_occurrence is exactly left-1? Then we are moving left to the same position? Actually, if the duplicate is at the left boundary, then we move left to left+1, which is correct.
But note: we are updating last_occurrence[s[right]] after we potentially move left. So when we check, we are using the old last_occurrence.
Let me adjust: we are using the old last_occurrence to decide whether to move left, and then we update to the current index.
This is correct.
However, there is an alternative: we can update the last_occurrence first and then set left = max(left, last_occurrence[s[right]] + 1). But note: if we update last_occurrence first, then the condition would be using the new index? That would be wrong because then we are using the current index (which is right) and then we set left to right+1? That doesn't make sense.
So we must use the old last_occurrence to decide.
Therefore, the code:
if s[right] in last_occurrence:
if last_occurrence[s[right]] >= left:
left = last_occurrence[s[right]] + 1
Then update last_occurrence[s[right]] = right
But note: what if the character hasn't been seen? Then we don't have it in the dictionary. So we can do:
if s[right] in last_occurrence:
if last_occurrence[s[right]] >= left:
left = last_occurrence[s[right]] + 1
last_occurrence[s[right]] = right
Alternatively, we can do:
if s[right] in last_occurrence and last_occurrence[s[right]] >= left:
left = last_occurrence[s[right]] + 1
last_occurrence[s[right]] = right
This is the same.
But note: what if the character is in the dictionary but its last occurrence is before left? Then we don't move left, and we update the last_occurrence to the current index. That's correct.
Let me code accordingly.
However, note: the problem says "only unique characters", meaning no duplicates.
We are returning the substring.
Let's write the function:
We assume the string can be empty? Then we return empty string.
Implementation:
if not s:
return ""
left = 0
max_len = 0
start = 0
last_occurrence = {}
for right, char in enumerate(s):
if char in last_occurrence and last_occurrence[char] >= left:
left = last_occurrence[char] + 1
last_occurrence[char] = right
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start+max_len]
Let's test with "abcabcbb" -> should return "abc" (or "bca", "cab" but the first one is at start=0, so "abc").
But note: when we are at right=3 (the second 'a'), we set left=1. Then the current window is [1,3] which is "bca", length=3. But we don't update max_len because 3 is not greater than 3. So we keep the first one.
That's acceptable because the problem says "longest", and if there are multiple, we can return any. But note: we are updating only when strictly greater, so we return the first one we found.
If we want the last one, we can change to >=. But the problem doesn't specify.
Let me test with "abba":
We found max_len=2 at start=0 (when right=1). Then at right=2, we have a duplicate 'b', so left=2. Then at right=3, we have 'a' which was last at 0, but 0<left(2) so we don't move left. Then current window [2,3] has length 2, but we don't update because 2 is not greater than 2. So we return "ab". But the substring "ba" is also valid and same length. So it's okay.
However, note that when we are at right=3, the window [2,3] is "ba", which is of length 2 and is the same as the current max. We are not updating, so we return the first one we found.
If we want the last one, we can change the condition to if current_len >= max_len and then update. But then we would update to the last one. But the problem doesn't specify which one to return.
Let me stick to the first one.
But note: the problem says "find the longest substring", so any is acceptable.
However, let me check the example: "abcabcbb" -> the longest are "abc", "bca", "cab". We return "abc" because we update at right=2 (when we first get 3) and then we don't update again because we never get more than 3.
So the code is:
def longest_unique_substring(s):
if not s:
return ""
left = 0
max_len = 0
start = 0
last_occurrence = {}
for right, char in enumerate(s):
if char in last_occurrence and last_occurrence[char] >= left:
left = last_occurrence[char] + 1
last_occurrence[char] = right
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start+max_len]
However, note: what if the string has only one character?
s="a":
right=0: char='a', not in last_occurrence -> then set last_occurrence['a']=0, current_len=1, max_len=1, start=0.
return s[0:1] -> "a". Correct.
What about empty string? We return "".
But wait, what if the string is all duplicates? e.g., "aaaa":
right=0: 'a' -> not in, last_occurrence['a']=0, current_len=1, max_len=1, start=0.
right=1: 'a' -> in and last_occurrence['a']=0 >= left(0) -> left=1.
then update last_occurrence['a']=1, current_len=1, no update.
right=2: 'a' -> in and last_occurrence['a']=1 >= left(1) -> left=2.
update last_occurrence['a']=2, current_len=1, no update.
right=3: 'a' -> in and last_occurrence['a']=2 >= left(2) -> left=3.
update last_occurrence['a']=3, current_len=1, no update.
return s[0:1] -> "a". Correct.
So it works.
But note: the condition last_occurrence[char] >= left is important because without it, when we have "abba", at the second 'a' (right=3) we would have last_occurrence['a']=0 and left=2, so 0<2 -> we don't move left. That's correct.
However, if we had done:
if char in last_occurrence:
left = max(left, last_occurrence[char] + 1)
Then for "abba":
right=0: 'a' -> last_occurrence['a']=0, left=0 -> no change.
right=1: 'b' -> last_occurrence['b']=1, left=0 -> no change.
right=2: 'b' -> last_occurrence['b']=1, left = max(0, 1+1)=2.
right=3: 'a' -> last_occurrence['a']=0, left = max(2, 0+1)=2.
So that also works and is more concise.
Let me change to:
if char in last_occurrence:
left = max(left, last_occurrence[char] + 1)
Then update last_occurrence[char] = right.
This is the same because if the last_occurrence is less than left, then we keep left. Otherwise, we set left to last_occurrence[char]+1.
So we can write:
for right, char in enumerate(s):
if char in last_occurrence:
left = max(left, last_occurrence[char] + 1)
last_occurrence[char] = right
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
This is simpler and avoids the explicit condition.
Let me test with "abba" again:
left=0, max_len=0, start=0.
right=0: char='a', not in -> last_occurrence['a']=0, current_len=1, max_len=1, start=0.
right=1: char='b', not in -> last_occurrence['b']=1, current_len=2, max_len=2, start=0.
right=2: char='b', in -> left = max(0, 1+1)=2.
update last_occurrence['b']=2, current_len=2-2+1=1, no update.
right=3: char='a', in -> left = max(2, 0+1)=2.
update last_occurrence['a']=3, current_len=3-2+1=2, no update.
return s[0:2] -> "ab". Correct.
And with "abcabcbb":
right=0: 'a' -> left=0, last_occurrence['a']=0, current_len=1, max_len=1, start=0.
right=1: 'b' -> left=0, last_occurrence['b']=1, current_len=2, max_len=2, start=0.
right=2: 'c' -> left=0, last_occurrence['c']=2, current_len=3, max_len=3, start=0.
right=3: 'a' -> in, left = max(0, 0+1)=1.
update last_occurrence['a']=3, current_len=3-1+1=3, no update.
right=4: 'b' -> in, left = max(1, 1+1)=2.
update last_occurrence['b']=4, current_len=4-2+1=3, no update.
right=5: 'c' -> in, left = max(2, 2+1)=3.
update last_occurrence['c']=5, current_len=5-3+1=3, no update.
right=6: 'b' -> in, left = max(3, 4+1)=5.
update last_occurrence['b']=6, current_len=6-5+1=2, no update.
right=7: 'b' -> in, left = max(5, 6+1)=7.
update last_occurrence['b']=7, current_len=7-7+1=1, no update.
return s[0:3] -> "abc". Correct.
So we can use the max version.
However, note: what if the character is not in last_occurrence? Then we don't change left.
So the code becomes:
def longest_unique_substring(s):
if not s:
return ""
left = 0
max_len = 0
start = 0
last_occurrence = {}
for right, char in enumerate(s):
if char in last_occurrence:
left = max(left, last_occurrence[char] + 1)
last_occurrence[char] = right
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start+max_len]
But wait, what if the string is very long? We are storing the last occurrence of every character we've seen. That's O(n) space.
However, if the string only contains a fixed set of characters (like ASCII), then the dictionary size is bounded by the character set. But in general, it's O(min(n, m)) where m is the character set size.
But note: the problem doesn't specify the character set, so we assume any character.
This is acceptable.
Let me test with an empty string, one char, and the examples.
We are done.
To solve the Longest Substring with Unique Characters problem, we use the sliding window technique with a hash map to track character positions. This ensures an optimal O(n) time complexity and O(min(n, m)) space complexity (where m is the character set size).
Algorithm Explanation
-
Initialize:
left = 0 (start of the current window)
max_len = 0 (length of the longest valid substring found)
start = 0 (starting index of the longest substring)
char_index = {} (maps characters to their most recent index)
-
Iterate with right pointer (end of window):
- If
s[right] is already in char_index and its last occurrence is within the current window (char_index[s[right]] >= left), move left to one position after that last occurrence to exclude the duplicate.
- Update
char_index[s[right]] to the current right index.
- Calculate current window length:
curr_len = right - left + 1.
- If
curr_len > max_len, update max_len and start.
-
Return the substring s[start:start + max_len].
Why This Works
- The window
[left, right] always contains unique characters because whenever a duplicate is found, left jumps past the previous occurrence.
- Each character is processed once by
right and at most once by left, leading to O(n) time.
- The hash map stores only the latest index per character, ensuring we can quickly adjust the window.
Python Implementation
def longest_unique_substring(s: str) -> str:
if not s:
return ""
left = 0
max_len = 0
start = 0
char_index = {}
for right, char in enumerate(s):
# If char seen and within current window, shrink window from left
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right # Update latest index
curr_len = right - left + 1
if curr_len > max_len:
max_len = curr_len
start = left
return s[start:start + max_len]
Example Walkthrough
For s = "abcabcbb":
right=0 ('a'): window [0,0] → length 1
right=1 ('b'): window [0,1] → length 2
right=2 ('c'): window [0,2] → length 3 (max so far)
right=3 ('a'): duplicate at index 0 → left=1, window [1,3] ("bca")
- ... continue, max remains 3
- Result:
"abc" (or any length-3 unique substring)
Complexity
- Time: O(n) — each character visited at most twice.
- Space: O(min(n, m)) — hash map stores at most one entry per unique character in the current window (bounded by character set size).