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.
Examples
Example 1:
Input: blocks = "WBBWWBBWBW", k = 7
Output: 3
Explanation:
One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks
so that blocks = "BBBBBBBWBW".
It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.
Therefore, we return 3.
Example 2:
Input: blocks = "WBWBBBW", k = 2
Output: 0
Explanation:
No changes need to be made, since 2 consecutive black blocks already exist.
Therefore, we return 0.
Constraints:
n == blocks.length
1 <= n <= 100
blocks[i]
is either'W'
or'B'
.1 <= k <= n
Solution
Method 1 - Using Sliding Window
Code
Java
class Solution {
public int minimumRecolors(String blocks, int k) {
int n = blocks.length();
int wCount = 0; // Count of white blocks in the current window
int ans = Integer.MAX_VALUE;
// Count 'W' in the first window of size k
for (int i = 0; i < k; i++) {
if (blocks.charAt(i) == 'W') {
wCount++;
}
}
ans = wCount;
// Slide the window over the string
for (int i = k; i < n; i++) {
// Add the new block to the window
if (blocks.charAt(i) == 'W') {
wCount++;
}
// Remove the first block of the previous window
if (blocks.charAt(i - k) == 'W') {
wCount--;
}
// Update the minimum operations
ans = Math.min(ans, wCount);
}
return ans;
}
}
Python
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
n = len(blocks)
w_count: int = 0 # Count of white blocks in the current window
ans: int = float('inf')
# Count 'W' in the first window of size k
for i in range(k):
if blocks[i] == 'W':
w_count += 1
ans = w_count
# Slide the window over the string
for i in range(k, n):
# Add the new block to the window
if blocks[i] == 'W':
w_count += 1
# Remove the first block of the previous window
if blocks[i - k] == 'W':
w_count -= 1
# Update the minimum operations
ans = min(ans, w_count)
return ans[LEO](https://leo.ai.pleo.io/chat/leo/a53889f0-556f-4fd9-8742-5b4aaa324b56)
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the stringblocks
, because we traverse the string once. - 🧺 Space complexity:
O(1)
since we only store variables for the count of white blocks and the minimum operations.