SDE & MLE Prep

3. Longest Substring Without Repeating Characters

Problem

Return the length of the longest substring of s that contains no repeated character.

Example: "abcabcbb" → 3 ("abc"); "bbbbb" → 1

Constraints: length ≤ 5·10⁴; letters, digits, symbols and spaces.

Keep the last index of each char. When s[r] was seen inside the window, jump l past that index.

a b c a b c b b
l     r          'a' last at 0 -> l = 1   window "bca"
best = 3

Complexity: O(n) time, O(min(n, alphabet)) space.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last = {}
        l = best = 0
        for r, ch in enumerate(s):
            if last.get(ch, -1) >= l:
                l = last[ch] + 1
            last[ch] = r
            best = max(best, r - l + 1)
        return best