Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nhudinhtuan/0ef426fa1e854632a0c208d2b151cc38 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/0ef426fa1e854632a0c208d2b151cc38 to your computer and use it in GitHub Desktop.
length of longest unique substring
from collections import defaultdict
def longest_unique_substring(s):
longest_length = float('-inf')
n = len(s)
# empty string has the longest length is 0
if n == 0:
return 0
left = 0
right = 0
window = defaultdict(int)
while right < n:
# sliding the window to the right
right_character = s[right]
window[right_character] += 1
right += 1
# if a duplicate character appears in the window
# drop off the left elements until we have valid condition again
while window[right_character] > 1:
window[s[left]] -= 1
left += 1
longest_length = max(longest_length, right - left)
return longest_length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment