Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
My solution

Mohammed Dh Abbas

Jul 9, 2024

class Solution: def findLength(self, text, k): max_length = float('-inf') freq = {} j = 0 most_freq_char = float('-inf') for i in range(len(text)): # update all characters frequencies char = text[i] freq[char] = freq.get(char, 0) freq[char] += 1 # track the most frequent character most_freq_char = max(most_freq_char, freq[char]) # total_len = the total length of the window # can_be_discarded_len = the length of the characters other than the most frequent character # can_be_discarded_len is what we use for knowing <= or > k total_len = i - j + 1 can_be_discarded_len = total_len - most_freq_char if can_be_discarded_len <= k: max_length = max(max_length, total_len) else: while can_be_discarded_len > k: # decrees the frequencies freq[text[j]] -= 1 # move j forward j += 1 # recalculate the remaining characters that has to be discarded from the left can_be_discarded_len -= 1 return max_length

0

0

Comments
Comments

On this page