Created
December 19, 2020 07:29
-
-
Save codecakes/13d913fdc799022eb3df379fb26515cd to your computer and use it in GitHub Desktop.
longest substring with no more than K distinct characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def longest_substring_with_k_distinct(chars, k): | |
left_idx = 0 | |
distinct_ct = 0 | |
max_ln = -1 | |
counter = defaultdict(int) | |
for right_idx, char in enumerate(chars): | |
# print("max_ln={}".format(max_ln)) | |
# print( | |
# "before IF: left_idx={} distinct_ct={} counter={}".format(left_idx, distinct_ct, counter)) | |
if not counter[char]: | |
distinct_ct += 1 | |
counter[char] += 1 | |
while distinct_ct > k: | |
left_chr = chars[left_idx] | |
if left_chr in counter: | |
counter[left_chr] -= 1 | |
if not counter[left_chr]: | |
distinct_ct -= 1 | |
# print( | |
# "left_idx={} left_chr={} distinct_ct={} counter={}".format( | |
# left_idx, left_chr, distinct_ct, counter)) | |
left_idx += 1 | |
max_ln = max(max_ln, right_idx - left_idx + 1) | |
# print( | |
# "after IF: left_idx={} distinct_ct={} counter={}".format(left_idx, distinct_ct, counter)) | |
return max_ln |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment