Skip to content

Instantly share code, notes, and snippets.

@deepanshumehtaa
Last active August 29, 2022 11:53
Show Gist options
  • Save deepanshumehtaa/a0777e69ffdabe89664a949ad1d929af to your computer and use it in GitHub Desktop.
Save deepanshumehtaa/a0777e69ffdabe89664a949ad1d929af to your computer and use it in GitHub Desktop.
# Best
def lengthOfLongestSubstring(self, s: str) -> int:
l = 0
r = 0
occ = {}
mx = 0
while r < len(s):
if s[r] not in occ:
occ[s[r]] = 1
r += 1
mx = r - l if r - l > mx else mx
elif occ[s[r]] == 0:
occ[s[r]] = occ[s[r]] + 1
r += 1
mx = r - l if r - l > mx else mx
elif occ[s[r]] > 0:
occ[s[l]] = occ[s[l]] - 1
l += 1
return mx
def lengthOfLongestSubstring(self, s: str) -> int:
left, right = 0, 0
answer = [left, right] # the window
diff = 0
hashset = defaultdict(int) # this will set 0 as default value to the key, if that key is not present
for i in s:
if hashset[i] == 0: # move the right pointer to the right, if there is no repetation
hashset[i] += 1
right += 1
else:
while hashset[i] >=1: # constrict the left pointer
hashset[s[left]] -= 1
left += 1
hashset[i] += 1 # update the current substring
right += 1
if right - left > diff: # update the window with longest substring
diff = right - left
answer[0], answer[1] = left, right
return answer[1] - answer[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment