[Python] Why is the time limited exceeded here?

  • 0

    I have a working solution I think, but I get a time limited exceeded. Can anyone tell me what I am missing?

    def lengthOfLongestSubstring(self, s):
        if len(s) <= 0:
            return 0
        max_count = 1
        letters = {}
        start = 0
        for i in range(len(s)):
            if s[i] in letters:
                if letters[s[i]] >= start:
                    temp_length = i - start
                    max_count = temp_length if temp_length > max_count else max_count
                    start = letters[s[i]] + 1
            letters[s[i]] = i
        return max_count

  • 0

    I think I found the problem. This if statement is wrong:

    if letters[s[i]] >= start:

    It should be:

    if letters[s[i]] + 1 >= start:

  • 0

    you didn't update your dictionary every time you encounter the repeating character

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.