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 to Get K Consecutive Black Blocks INPUT blocks = "WBBWWBBW" 0 1 2 3 4 5 6 7 W B B W W B B W n = 8 (length) k = 3 (target consecutive) Goal: k consecutive B's Legend: = White (W) = Black (B) ALGORITHM STEPS 1 Sliding Window Use window of size k=3 2 Count W's in Window W count = recolors needed 3 Slide and Update Track min W's across all 4 Return Minimum Answer is minimum count Window Positions: [0-2]: WBB W=1 [1-3]: BBW W=1 [2-4]: BWW W=2 [3-5]: WWB W=2 [4-6]: WBB W=1 [5-7]: BBW W=1 Min W count = 1 FINAL RESULT Best window: positions [0-2] Before (WBB): W B B Recolor 1 white block After (BBB): B B B Output: 1 1 operation needed Key Insight: The sliding window technique converts "find k consecutive blacks" into "find window with minimum whites". Each white block in a window of size k needs exactly one recolor operation. Time complexity: O(n), Space: O(1). TutorialsPoint - Minimum Recolors to Get K Consecutive Black Blocks | Optimal Sliding Window Approach
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