BudiBadu Logo

Minimum Recolors To Get K Consecutive Black Blocks

Sliding Window Easy 2 views
Like0

In Minimum Recolors To Get K Consecutive Black Blocks, you receive a string blocks made of 'W' and 'B', plus an integer k. You can recolor white blocks to black, and you need the minimum number of recolors required so at least one contiguous segment of length k becomes fully black.

The key idea is simple: for any window of size k, the number of recolors needed is exactly how many 'W' characters are in that window. So the real task is finding the minimum white count among all length-k windows. A fixed sliding window makes this efficient: initialize the first window, then update counts as one character enters and one leaves.

The judge checks easy and tricky scenarios, including already-black windows requiring zero changes, all-white stretches, and alternating patterns where only one recolor may be needed. Your function should return a single integer minimum, with no extra output, and the answer must be based on contiguous windows only for every tested case.

Examples

Example 1
Input
blocks = "WBBWWBBWBW", k = 7
Output
3
Explanation

Best size-7 window contains 3 white blocks.

Example 2
Input
blocks = "WBWBBBW", k = 2
Output
0
Explanation

Window "BB" already satisfies the requirement.

Example 3
Input
blocks = "WWWW", k = 2
Output
2
Explanation

Need to recolor both blocks in any window.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Recolors To Get K Consecutive Black Blocks - Budibadu
Recommendation Algorithm Flow for Minimum Recolors To Get K Consecutive Black Blocks - Budibadu

Best Answers

java
class Solution {
    public int minimum_recolors_to_get_k_consecutive_black_blocks(String blocks, int k) {
        int n = blocks.length();
        if (k <= 0 || k > n) return 0;
        int white = 0;
        for (int i = 0; i < k; i++) if (blocks.charAt(i) == 'W') white++;
        int best = white;
        for (int i = k; i < n; i++) {
            if (blocks.charAt(i) == 'W') white++;
            if (blocks.charAt(i-k) == 'W') white--;
            if (white < best) best = white;
        }
        return best;
    }
}