Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created December 25, 2020 06:02
Show Gist options
  • Save codecakes/32060bef4dc321258b87dce80e1fb5f3 to your computer and use it in GitHub Desktop.
Save codecakes/32060bef4dc321258b87dce80e1fb5f3 to your computer and use it in GitHub Desktop.
Longest substring without any repeating characters
def non_repeat_substring(string):
from collections import Counter
max_ctr = Counter()
left_idx = 0
distinct = 0
max_distinct = float('-inf')
for right_idx, r_char in enumerate(string):
if not max_ctr[r_char]:
distinct += 1
max_ctr[r_char] += 1
while max_ctr[r_char] > 1:
l_char = string[left_idx]
max_ctr[l_char] -= 1
if not max_ctr[l_char]:
distinct -= 1
left_idx += 1
max_distinct = max(max_distinct, distinct)
return max_distinct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment