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 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 blocks

Example: 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
Sliding Window VisualizationInput: "WBBWWBBWBW" k=7Step 1: Initial Window (0-6)WBBWWBBWhite blocks: 3, Min so far: 3Step 2: Slide Window (1-7)BBWWBBWRemoved W, Added W → White: 3, Min: 3Step 3: Slide Window (2-8)BWWBBWBRemoved B, Added B → White: 3, Min: 3🎯 Key Insight: Update count incrementally for O(n) efficiency!Final Answer: 3 (minimum white blocks in any window of size 7)
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.
Asked in
Amazon 25 Microsoft 18 Google 15 Meta 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen