Minimum Recolors to Get K Consecutive Black Blocks (LeetCode 2379): Solution and Explanation

Easy
String
Sliding Window

Return the fewest white blocks you must repaint black so that some run of k consecutive blocks is entirely black.

Intuition

The k black blocks have to occupy some window of exactly k consecutive positions, and there are only n - k + 1 such windows.

To make one fixed window all black you repaint exactly the white blocks inside it, no more and no fewer. So the cost of a window is its white count.

The answer is the smallest white count over all windows. Neighbouring windows share k - 1 blocks, so moving the window one step changes the count only through the block that enters and the block that leaves.

Approach: Fixed-size sliding window

  1. Count the white blocks in blocks[0..k-1] and store it in whites. Set best = whites.
  2. For each i from k to n - 1, add one to whites if blocks[i] is white.
  3. Subtract one if blocks[i - k], the block leaving the window, is white.
  4. Set best = min(best, whites).
  5. Return best.

Step-by-step example

blocks = "WBBWWBBWBW", k = 7
  1. The first window "WBBWWBB" (indices 0..6) holds 3 whites. whites = 3, best = 3.
  2. i = 7: a white enters and the white at index 0 leaves. Window "BBWWBBW" still holds 3 whites.
  3. i = 8: a black enters and a black leaves. Window "BWWBBWB" holds 3 whites.
  4. i = 9: a white enters and a black leaves. Window "WWBBWBW" holds 4 whites, worse than 3.
  5. Every window was checked and the smallest count is 3, so the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def minimumRecolors(self, blocks: str, k: int) -> int:
3        whites = blocks[:k].count('W')
4        best = whites
5        for i in range(k, len(blocks)):
6            if blocks[i] == 'W':
7                whites += 1
8            if blocks[i - k] == 'W':
9                whites -= 1
10            best = min(best, whites)
11        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each block enters the window once and leaves at most once, and each event is a single comparison.

Space

O(1)

Only the running white count and the best count are stored.

Other approaches

Prefix count of whites (time O(n), space O(n))

Build pre[i], the number of whites in blocks[0..i-1]. The window starting at j costs pre[j + k] - pre[j], and the answer is the minimum over j.

Recount every window (time O(n * k), space O(1))

For each start, count the whites in the next k blocks. With n at most 100 this passes, but it does O(nk) work and does not scale.

Common mistakes

  • Counting black blocks and returning k minus the maximum works too, but mixing the two (maximising whites or minimising blacks) gives the wrong answer.
  • Removing blocks[i - k + 1] instead of blocks[i - k]. The block that leaves when index i enters is exactly k positions behind it.
  • Forgetting the first window when initialising best. When k equals n it is the only window.
  • Looking for the longest existing black run is not enough: a window with a few scattered whites can be cheaper than extending the longest run.

Frequently asked questions

Why is the cost of a window exactly its number of white blocks?

Black blocks inside the window need nothing, every white block inside it must be repainted, and blocks outside it do not matter. So the cheapest way to make that window black repaints exactly its whites.

Can I stop early?

Yes. A window cannot cost less than 0, so once best reaches 0 you can return immediately.

Is this the same trick as Max Consecutive Ones III?

It is related but simpler. There the window length is free and the number of flips is fixed; here the length is fixed at k and you minimise the flips, so the left edge always moves with the right edge.