You are given a string blocks
of length n
where each character is either ‘W’ or ‘B’, representing white or black blocks respectively. You are also given an integer k
, the number of consecutive black blocks you want. The task is to determine the minimum number of recolors needed to get at least k
consecutive black blocks.
1 <= k <= n <= 100
blocks[i]
is either ‘W’ or ‘B’k
consecutive ‘B’ blocks.k
to traverse through the blocks
string.k
consecutive black blocks.k
characters) and count the number of ‘W’ blocks.def minimumRecolors(blocks: str, k: int) -> int:
# Initialize the minimum recolors to a large number.
min_recolors = float('inf')
# Count the number of 'W' in the initial window of size k.
current_recolors = blocks[:k].count('W')
# Initialize min_recolors with the first window's count of 'W'
min_recolors = min(min_recolors, current_recolors)
# Slide the window across the string, updating counts.
for i in range(1, len(blocks) - k + 1):
# Check the character that is leaving the window
if blocks[i - 1] == 'W':
current_recolors -= 1
# Check the character that is entering the window
if blocks[i + k - 1] == 'W':
current_recolors += 1
# Update the minimum recolors needed
min_recolors = min(min_recolors, current_recolors)
return min_recolors
O(k)
.O(1)
.n-k+1
positions), making the overall time complexity O(n)
.This approach efficiently finds the minimum recolors required to achieve at least k
consecutive ‘B’ blocks.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?