Minimum Recolors to Get K Consecutive Black Blocks - Problem
You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively.
You are also given an integer k, which is the desired number of consecutive black blocks.
In one operation, you can recolor a white block such that it becomes a black block.
Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.
Input & Output
Example 1 — Basic Case
$
Input:
blocks = "WBBWWBBW", k = 3
›
Output:
1
💡 Note:
We can change blocks[0] from 'W' to 'B' to get "BBBWWBBW", which has 3 consecutive black blocks at the beginning.
Example 2 — Already Optimal
$
Input:
blocks = "WBWBBBWBW", k = 3
›
Output:
0
💡 Note:
There are already 3 consecutive black blocks (BBB) in the string, so no operations are needed.
Example 3 — All White
$
Input:
blocks = "WWWWW", k = 2
›
Output:
2
💡 Note:
We need to change any 2 consecutive white blocks to black blocks, requiring 2 operations.
Constraints
- 1 ≤ blocks.length ≤ 100
- blocks[i] is either 'W' or 'B'
- 1 ≤ k ≤ blocks.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
String of W (white) and B (black) blocks with target k
2
Find Window
Find k-length window with minimum white blocks
3
Result
Return count of white blocks that need recoloring
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the k-length substring with minimum white blocks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code