Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

To find the longest substring without repeating characters, we need to keep track of the last seen index of each character and use a sliding window to ensure all characters in the current window are unique.

Approach

Complexity

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        chars_index = [-1] * 128
        left, right = 0, 0
        res = -float("inf")

        for right in range(len(s)):
            ch_ascii = ord(s[right])

            ch_index = chars_index[ch_ascii]

            while ch_index != -1 and (left <= ch_index <= right):
                left = ch_index + 1

            chars_index[ch_ascii] = right
            res = max(res, right - left + 1)

        return int(res if res >= 0 else 0)

Back to Problem Statement