Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Examples
s = 'abcabcbb'
3
The answer is 'abc', with the length of 3.
s = 'bbbbb'
1
The answer is 'b', with the length of 1.
s = 'pwwkew'
3
The answer is 'wke', with the length of 3.
Constraints
- •
0 <= s.length <= 5 * 10^4 - •
s consists of English letters, digits, symbols and spaces.
Approaches
Generate all substrings and check if they contain repeating characters.
def length_of_longest_substring(s):
def has_no_repeats(sub):
return len(sub) == len(set(sub))
max_len = 0
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if has_no_repeats(s[i:j]):
max_len = max(max_len, j - i)
return max_lenUse a sliding window with a set to track characters.
def length_of_longest_substring(s):
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_len = max(max_len, right - left + 1)
return max_lenUse a hash map to store the last index of each character, allowing direct jumps.
Diagram
def length_of_longest_substring(s):
char_index = {}
left = 0
max_len = 0
for right in range(len(s)):
if s[right] in char_index and char_index[s[right]] >= left:
left = char_index[s[right]] + 1
char_index[s[right]] = right
max_len = max(max_len, right - left + 1)
return max_lenComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Brute Force | O(n^3) | O(min(n, m)) | Generate all substrings and check if they contain repeating characters. |
| Sliding Window with Set | O(n) | O(min(n, m)) | Use a sliding window with a set to track characters. |
| Sliding Window with HashMap | O(n) | O(min(n, m)) | Use a hash map to store the last index of each character, allowing direct jumps. |
Generate all substrings and check if they contain repeating characters.
Use a sliding window with a set to track characters.
Use a hash map to store the last index of each character, allowing direct jumps.
Common Mistakes
Using a fixed-size array instead of a hash map for character tracking
Not updating the left pointer correctly when a duplicate is found
Confusing substring (contiguous) with subsequence (non-contiguous)