https://leetcode.com/problems/longest-repeating-character-replacement/
Q: Given a string s
that consists of only uppercase English letters, you can perform at most k
operations on that string. In one operation, you can choose any character of the string and change it to any other character. Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.
Here’s my description of the same problem:
Q: Suppose we stand by highway and watch cars of the each color. Only 26 possible colors. Cars pass fast, so sometimes we miscount.
My son says “I saw 11 red cars in a row in the fast lane”.
My daughter says “I saw 22 blue cars in a row in the middle lane”
We allow kids to miss up to 3 cars in their answer. In other words, my son may have seen only 8, 9 or 10 red cars in a row.
When we review the traffic video footage of N cars in a single lane, determine the max X cars in a row of the same color, allowing k mistakes. K < N.
====analysis
Suppose k is 3
— solution 1: O(N) use 2 variables to maintain topFrq and w i.e. winSize
Within a sliding window of size w, maintain a frq table. initialize w to a good conservative value of 4 (i.e. k+1).
If we notice top frq is 2, better than (w-k) i.e. w-k<=topFrq , then lucky we can be less conservative and we can expand the current window backward (possibly safer than fwd).
After expansion, immediate try further expansion. IFF impossible i.e. w – topFrq > k, then slide the window.
If correct answer is 11 i.e there’s a 11-substring containing 8 reds, I feel my sliding window will not miss it.