Minimum Recolors to Get K Consecutive Black Blocks - Problem
Painting Challenge: Transform a row of blocks to create a sequence of consecutive black blocks!
You're given a string
The Rules:
• You can only change white blocks ('W') to black blocks ('B')
• You cannot change black blocks to white
• You need at least one occurrence of
Example: If
You're given a string
blocks where each character represents a colored block: 'B' for black and 'W' for white. Your goal is to find the minimum number of white blocks you need to repaint to black in order to have at least k consecutive black blocks.The Rules:
• You can only change white blocks ('W') to black blocks ('B')
• You cannot change black blocks to white
• You need at least one occurrence of
k consecutive black blocksExample: If
blocks = "WBBWWBBWBW" and k = 7, you need to find the best window of 7 consecutive positions and count how many white blocks need to be painted black. Input & Output
example_1.py — Basic Case
$
Input:
blocks = "WBBWWBBWBW", k = 7
›
Output:
3
💡 Note:
We need a window of 7 consecutive blocks. The optimal window is from index 1 to 7: "BBWWBBW". This contains 3 white blocks that need to be recolored to black.
example_2.py — All Black
$
Input:
blocks = "BBBBBB", k = 4
›
Output:
0
💡 Note:
We already have more than 4 consecutive black blocks, so no recoloring is needed. Any window of size 4 will have 0 white blocks.
example_3.py — All White
$
Input:
blocks = "WWWWWW", k = 3
›
Output:
3
💡 Note:
All blocks are white, so any window of size 3 will require recoloring all 3 white blocks to black.
Constraints
- 1 ≤ blocks.length ≤ 100
- blocks[i] is either 'W' or 'B'
- 1 ≤ k ≤ blocks.length
- k cannot be larger than the total number of blocks
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Window
Start with the first k blocks and count white blocks
2
Slide and Update
Move window right, remove left element, add right element
3
Track Minimum
Keep track of the minimum white count across all windows
4
Return Result
The minimum white count is our answer
Key Takeaway
🎯 Key Insight: The sliding window technique transforms this from an O(n×k) problem to O(n) by maintaining a running count and updating it incrementally rather than recounting the entire window each time.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code