I am solving LeetCode problem https://leetcode.com/problems/longest-substring-without-repeating-characters/:
Given a string
s, find the length of the longest substring without repeating characters.Constraints:
0 <= s.length <= 5 * 104sconsists of English letters, digits, symbols and spaces.
If used this sliding window algorithm:
def lengthOfLongestSubstring(str):
# define base case
if (len(str) < 2): return len(str)
# define pointers and frequency counter
left = 0
right = 0
freqCounter = {} # used to store the character count
maxLen = 0
while (right < len(str)):
# adds the character count into the frequency counter dictionary
if (str[right] not in freqCounter):
freqCounter[str[right]] = 1
else:
freqCounter[str[right]] += 1
# print (freqCounter)
# runs the while loop if we have a key-value with value greater than 1.
# this means that there are repeated characters in the substring.
# we want to move the left pointer by 1 until that value decreases to 1 again. E.g., {'a':2,'b':1,'c':1} to {'a':1,'b':1,'c':1}
while (len(freqCounter) != right-left+1):
# while (freqCounter[str[right]] > 1): ## Time Limit Exceeded Error
print(len(freqCounter), freqCounter)
freqCounter[str[left]] -= 1
# remove the key-value if value is 0
if (freqCounter[str[left]] == 0):
del freqCounter[str[left]]
left += 1
maxLen = max(maxLen, right-left+1)
# print(freqCounter, maxLen)
right += 1
return maxLen
print(lengthOfLongestSubstring("abcabcbb")) # 3 'abc'
I got the error "Time Limit Exceeded" when I submitted with this while loop:
while (freqCounter[str[right]] > 1):
instead of
while (len(freqCounter) != right-left+1):
I thought the first is accessing an element in a dictionary, which has a time complexity of O(1). Not sure why this would be significantly slower than the second version. This seems to mean my approach is not optimal in either case. I thought sliding window would be the most efficient algorithm; did I implement it wrong?