Grokking LinkedIn Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
more efficient solution

lestatcheb

Jun 26, 2024

Looks like the provided solution is not perfect, when we found a duplicate char - we should jump the left pointer to the prev duplicate char position + 1 instead of just doing start += 1

class Solution2: def lengthOfLongestSubstring(self, s: str) -> int: # key: char # value: index of char in s m = {} max_length = 0 # init to 0, to handle empty string cases left = 0 for right in range(len(s)): c = s[right] # if found a duplicate, and it's in the current window, # move left to the next non-duplicate position if c in m and m[c] >= left: left = m[c] + 1 m[c] = right cur_length = right - left + 1 max_length = max(max_length, cur_length) return max_length

3

0

Comments
Comments

On this page