Given a string s, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
We can use a sliding window approach to solve this problem:
Time Complexity: O(n) where n is the length of the string. Each character is processed at most twice (once by right pointer, once by left pointer).
Space Complexity: O(min(m, n)) where m is the size of the character set. In the worst case, the set may contain all characters in the string.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = set()
left = 0
max_len = 0
for right, ch in enumerate(s):
# If character is already in our window, shrink window from left
while ch in seen:
seen.remove(s[left])
left += 1
# Add current character to window
seen.add(ch)
# Update maximum length
max_len = max(max_len, right - left + 1)
return max_len