Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. Tags: String

Try It!

Discussion

Video

Solution

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        chars_used = set()

        l = 0
        r = 0

        max_len = 0

        while r < len(s):
            c_r = s[r]
            if c_r not in chars_used:
                chars_used.add(c_r)
                if r - l + 1 > max_len:
                    max_len = r - l + 1
                r += 1
            else:
                c_l = s[l]
                chars_used.remove(c_l)
                l += 1
        
        return max_len