3. Longest Substring Without Repeating Characters¶
Summary¶
| Solution Approach | Explanation (1-minute) | Time Complexity | Space Complexity |
|---|---|---|---|
| Brute Force | Check all possible substrings and verify each one has unique characters using nested loops. | \(O(n^2)\) | \(O(min(m,n))\) |
| Sliding Window (Two Pointers) | Use left and right pointers with a set to track characters. When duplicate found, shrink window from left until duplicate removed. | \(O(n)\) | \(O(min(m,n))\) |
| Sliding Window (Length Tracking) | Similar approach but tracks substring length directly instead of using two pointers. Removes characters from the beginning when duplicates found. | \(O(n)\) | \(O(min(m,n))\) |
Implementation¶
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_length = 0
chars = set()
left = 0
for right in range(len(s)):
while s[right] in chars:
chars.remove(s[left])
left += 1
chars.add(s[right])
max_length = max(
max_length,
len(s[left:right+1])
)
return max_length
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_length = 0
char_set = set()
len_substr = 0
for i in range(len(s)):
while s[i] in char_set:
char_set.remove(s[i-len_substr])
len_substr -= 1
char_set.add(s[i])
len_substr += 1
max_length = max(
max_length,
len_substr
)
return max_length