Longest Substring Without Repeating Characters in Python

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # Initialize a set to keep track of characters currently in the window.
        char_set = set()

        # Initialize the left pointer for the window and the maximum length found.
        left = 0
        max_length = 0

        # Iterate through the string with the right pointer (i).
        for right in range(len(s)):
            # If the character at the right pointer is in the set, it's a repeating character.
            # We remove characters from the set and move the left pointer until the character is removed.
            while s[right] in char_set:
                char_set.remove(s[left])
                left += 1

            # Add the current character to the set and move the right pointer forward.
            char_set.add(s[right])

            # Calculate the length of the current substring and update max length if necessary.
            max_length = max(max_length, right - left + 1)

        # Return the maximum length found.
        return max_length

PrevNext