longest-repeating-character-replacement py3
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
# Time: O(N^2)
|
||||
# Space: O(N)
|
||||
|
||||
from collections import Counter
|
||||
|
||||
class Solution:
|
||||
def characterReplacement(self, s: str, k: int) -> int:
|
||||
'''
|
||||
Sliding window approach
|
||||
'''
|
||||
|
||||
def window_size(l, r):
|
||||
return r - l + 1
|
||||
|
||||
# Need to keep track of frequency of each character in the
|
||||
# window
|
||||
count = Counter()
|
||||
l = r = 0
|
||||
result = 0
|
||||
|
||||
while r < len(s):
|
||||
# Increment the frequency of the `r`th char
|
||||
count.update(s[r])
|
||||
|
||||
# We can perform upto K replacements. So we prefer least num
|
||||
# of replacements (<= K). In the current window, we can perform
|
||||
# least replacements for the most common character in the range.
|
||||
#
|
||||
# e.g. AAABB K=2, in range 0 to 4, most common char is A, count=3
|
||||
# so it just needs 5 - 3 = 2 replacements which is <= K which is ok.
|
||||
#
|
||||
# But, if K = 1, then we need 5 - 2 = 2 replacements for the same range
|
||||
# but 2 > K so this window is not valid. We need to move left pointer in
|
||||
# this case and reduce its count.
|
||||
if window_size(l, r) - count.most_common(1)[0][1] > k:
|
||||
count.subtract(s[l])
|
||||
l += 1
|
||||
|
||||
result = max(result, window_size(l, r))
|
||||
r += 1
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,43 @@
|
||||
# Time: O(N)
|
||||
# Space: O(N)
|
||||
|
||||
from collections import Counter
|
||||
|
||||
class Solution:
|
||||
def characterReplacement(self, s: str, k: int) -> int:
|
||||
'''
|
||||
Sliding window approach, optimized
|
||||
'''
|
||||
|
||||
def window_size(l, r):
|
||||
return r - l + 1
|
||||
|
||||
# Need to keep track of frequency of each character in the
|
||||
# window
|
||||
count = Counter()
|
||||
|
||||
# We can optimize the prev sliding window approach by just keeping
|
||||
# track of maximum frequency/count of an element we've seen so far.
|
||||
maxf = 0
|
||||
|
||||
l = r = 0
|
||||
result = 0
|
||||
|
||||
while r < len(s):
|
||||
# Increment the frequency of the `r`th char
|
||||
count.update(s[r])
|
||||
|
||||
# If right's frequency is bigger, make it the new
|
||||
# max frequency
|
||||
maxf = max(maxf, count[s[r]])
|
||||
|
||||
# Refer to neetcode: https://www.youtube.com/watch?v=gqXU1UyA8pk
|
||||
# TODO: Document this approach my own way
|
||||
if window_size(l, r) - maxf > k:
|
||||
count.subtract(s[l])
|
||||
l += 1
|
||||
|
||||
result = max(result, window_size(l, r))
|
||||
r += 1
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user