src.longest_rep_char_replacement¶
Classes
|
- class src.longest_rep_char_replacement.Solution[source][source]¶
- characterReplacement(s: str, k: int) int [source]¶
Thought process¶
Again a siliding window problem
The idea here is that our target substring consists of two components
The most frequent character
The rest of the \(k\) other characters (which we can flip to the most frequent character)
So we keep track of the most frequent character through a basic frequency map
Now a trick we can do is we can break the letters in two types
belongs to the subword
does not belong to the subword
Clearly if we can just deliniate ( separate ) the two, we can easily find the length of the subword by doing
all letters - violating letters
So we can define our
l
pointer as the point which separates the two types of characters, in the most simple sense alll
is, is a counter of the violating characters, that is, everytime we have the violating conditionr - l + 1 - maxf > k
we incrementl
by 1, and decrement the frequency of the character atl
by 1The violating condition
r - l + 1 - maxf > k
is just a way of saying that the rest of the characters in our substring exceed the number of characters we can flip
Notes¶
time complexity is \(O(n)\)
space complexity is \(O(1)\)