We use the Sliding Window technique with two pointers and a hash map (or set) to track the indices of characters seen so far.
start = 0,max_len = 0.used = {}(map char to last seen index).- For
endfrom 0 tolen(s) - 1:- If
s[end]is inusedandused[s[end]] >= start:- Move
starttoused[s[end]] + 1.
- Move
- Update
max_len = max(max_len, end - start + 1). - Update
used[s[end]] = end.
- If
- Return
max_len.
- Time Complexity: O(N).
- Space Complexity: O(min(M, N)), where M is the size of the charset.
def length_of_longest_substring(s):
used = {}
max_len = start = 0
for i, char in enumerate(s):
if char in used and start <= used[char]:
start = used[char] + 1
else:
max_len = max(max_len, i - start + 1)
used[char] = i
return max_len