Longest Substring Without Repeating Characters

LeetCode 3 · View on LeetCode

Sliding window with a dict tracking the last index of each character. When a duplicate is found, jump the left pointer past the previous occurrence.

def length_of_longest_substring(s: str) -> int:
    last_seen = {}
    left = 0
    result = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1
        last_seen[ch] = right
        result = max(result, right - left + 1)
    return result

if __name__ == '__main__':
    print(length_of_longest_substring("abcabcbb"))  # 3
    print(length_of_longest_substring("bbbbb"))     # 1
    print(length_of_longest_substring("pwwkew"))    # 3
© 2026 ByteLearn.dev. Free courses for developers. · Privacy