Jump left directly using a map of last positions.
function lengthOfLongestSubstring(s):
charIndex = empty map
left = 0, maxLen = 0
for right from 0 to s.length - 1:
if s[right] in charIndex and charIndex[s[right]] >= left:
left = charIndex[s[right]] + 1
charIndex[s[right]] = right
maxLen = max(maxLen, right - left + 1)
return maxLen
Improvement: Skip multiple characters at once instead of shrinking one by one.
Time: . Space: .