Sliding Window
24 / 170Sliding WindowLesson 3 of 6About 52 min
Sometimes the window is legal or not based on a number you have to derive rather than read.
In the last lesson, legality was something you could read directly: a total, a count of distinct characters. Now consider a window that is allowed a limited number of changes.
The concrete version: given a list of 0s and 1s, and a budget of k flips from 0 to 1, what is the longest stretch you can make all 1s?
A window holds the characters AABABBA and you may replace characters to make them all identical. How many replacements does it need, and how is that computed?
This is meant to find the longest stretch with at most k zeros. It reports windows that are too long. Click the line that is wrong.
Time and space for longest_all_ones_after_flips on a list of n bits.
left = 0zeros = 0best = 0for right in range(len(bits)): if bits[right] == 0: zeros += 1 while zeros > k: if bits[left] == 0: zeros -= 1 left += 1 best = max(best, right - left + 1)Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.