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
Minimum Recolors for K Consecutive Black BlocksInput: blocks = "WBBWWBBW", k = 3WBBWWBBWOriginal blocksCheck all possible k=3 windowsBBBWWBBWOptimal window: 1 recolor neededAnswer: 1Change 1 white to blackto get BBBSliding window finds minimum operations in O(n) time
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
Asked in
Microsoft 15 Amazon 12 Apple 8
23.4K 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