Longest Substring Without Repeating Characters

Problem Id: 3 Difficulty: Medium Tag: Hash Table Tag: Two Pointers Tag: String Tag: Sliding Window


Intuition

This is a typical sliding window problem.

Solution


from collections import defaultdict


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        count = defaultdict(int)
        lo = 0
        hi = 0
        max_length = 0
        while hi < len(s):
            new = s[hi]
            count[new] += 1
            hi += 1
            while count[new] > 1:
                count[s[lo]] -= 1
                lo += 1
            max_length = max(max_length, hi - lo)
        return max_length