We use a sliding window with two pointers (left and right) and a hash map to store the last seen index of each character.
l = 0,res = 0.char_map = {}.- For
rfrom 0 tolen(s)-1:- If
s[r]is inchar_map:- Update
l = max(l, char_map[s[r]] + 1).
- Update
- Update
res = max(res, r - l + 1). char_map[s[r]] = r.
- If
- Return
res.
- Time Complexity: O(N).
- Space Complexity: O(min(N, M)) where M is the charset size.
def length_of_longest_substring(s):
l = 0
res = 0
char_map = {}
for r in range(len(s)):
if s[r] in char_map:
l = max(l, char_map[s[r]] + 1)
res = max(res, r - l + 1)
char_map[s[r]] = r
return res