Taro Logo

Minimum Recolors to Get K Consecutive Black Blocks

#1 Most AskedEasy
1 view
Topics:
ArraysStringsSliding Windows

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.

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the length constraints of the `blocks` string, and what is the valid range for `k`?
  2. Is it guaranteed that `k` is always less than or equal to the total length of the `blocks` string?
  3. Can the `blocks` string contain characters other than 'W' and 'B'?
  4. If the `blocks` string already contains at least `k` consecutive black blocks, should the function return 0?
  5. What should be returned if `k` is 0?

Brute Force Solution

Approach

Imagine you have a row of colored blocks, some white and some black, and you want to find a group of a specific size where you can paint the fewest white blocks to make them all black. The brute force approach works by looking at every possible group of that exact size one by one and counting how many blocks need to be painted in each group.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first group of blocks of the required target size.
  2. Count how many white blocks are hiding inside this first group, because those are the ones you would need to paint.
  3. Remember this count, and then shift your attention slightly to the right to look at the next possible group of the exact same size.
  4. Repeat this counting process for every single possible group of that size from the beginning of the row all the way to the end.
  5. Compare the counts you collected from every single group you examined.
  6. Finally, pick the smallest count you found, which tells you the fewest painting actions needed for any group of that size.

Code Implementation

def minimum_recolors(block_string, target_size):
    minimum_paint_count = target_size
    
    # We check every possible window of size k to find the one requiring the least paint effort
    for start_index in range(len(block_string) - target_size + 1):
        current_white_count = 0
        
        # We count white blocks inside the current window because those represent required operations
        for current_index in range(start_index, start_index + target_size):
            if block_string[current_index] == 'W':
                current_white_count += 1
        
        # We keep track of the smallest white block count found across all evaluated windows
        if current_white_count < minimum_paint_count:
            minimum_paint_count = current_white_count
            
    return minimum_paint_count

Big(O) Analysis

Time Complexity
O(n * k) – For each of the n blocks in the row, we must check a group of size k to count how many white blocks need to be recolored. The first step involves inspecting the initial group of size k, and subsequent steps slide this window across all n - k + 1 possible positions. This inspection process repeats k operations for approximately n starting positions. The total operations approximate n * k, which simplifies to O(n * k) in the worst case where k is proportional to n.
Space Complexity
O(1) – The algorithm only uses a few primitive variables to track the current count of white blocks, the minimum count found, and loop indices. These variables consume a constant amount of memory regardless of the input string length N. Since no additional data structures scale with the input size, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

Instead of checking every single possibility from scratch, the optimal approach uses a sliding window strategy to keep track of changes efficiently. It looks at a fixed-size section of items at a time and simply slides that viewing frame across the entire sequence.

Here's how the algorithm would work step-by-step:

  1. Create a viewing frame that is exactly the target size wide and place it at the very beginning of the sequence.
  2. Count how many white items currently fall inside this initial frame, because those are the ones we would need to change.
  3. Remember this count as our starting best score for the fewest changes needed.
  4. Slide the frame one spot to the right by letting the item on the far left exit the frame and a new item on the far right enter.
  5. Update our count of white items inside the frame based on only the single item that left and the single item that arrived, avoiding the need to recount everything from scratch.
  6. Compare this new count with our previous best score and keep the smaller number.
  7. Repeat the sliding and updating process until the frame reaches the very end of the sequence, ensuring we find the absolute minimum changes required.

Code Implementation

def minimum_recolors(block_sequence, target_k):    # Establish initial window to evaluate the first segment of required length.    initial_white_count = block_sequence[:target_k].count('W')    minimum_changes_needed = initial_white_count    # Slide window across remaining elements for efficient constant-time updates.    for current_index in range(target_k, len(block_sequence)):        if block_sequence[current_index - target_k] == 'W':            initial_white_count -= 1        if block_sequence[current_index] == 'W':            initial_white_count += 1        minimum_changes_needed = min(minimum_changes_needed, initial_white_count)    # Return the absolute minimum white blocks found in any sliding window.    return minimum_changes_needed

Big(O) Analysis

Time Complexity
O(n) – To find the minimum recolors, we first iterate through the first k elements of the string of length n to set up our initial sliding window count. We then slide this window one character at a time across the remaining elements of the string, performing constant time updates by adding the incoming character and subtracting the outgoing character. Since each of the n elements enters and leaves the window a constant number of times, this results in approximately n operations. Therefore, the linear progression simplifies to O(n).
Space Complexity
O(1) – The sliding window algorithm only utilizes a few primitive integer variables to track the current count of white items, the window indices, and the running minimum score. Because these variables require a fixed amount of memory regardless of the input size, no extra data structures scale with the sequence length N. Therefore, the auxiliary space complexity remains constant at O(1).

Edge Cases

k is equal to the length of the blocks string
How to Handle:
The sliding window size matches the entire string, so we simply count and return the number of 'W' characters in the whole string.
k is 1
How to Handle:
The sliding window of size 1 will check each character individually, and the minimum recolors will be 0 if at least one 'B' exists or 1 otherwise.
The string contains only 'B' characters
How to Handle:
The number of white blocks in any window of size k will be 0, correctly resulting in 0 total operations.
The string contains only 'W' characters
How to Handle:
Every window of size k will consist entirely of whites, meaning the minimum recolors will equal k.
String length is very large up to the maximum constraints
How to Handle:
An O(n) sliding window approach processes the elements in a single pass without extra memory overhead, easily handling large inputs efficiently.
k is greater than the length of the blocks string
How to Handle:
This is logically impossible per problem constraints, but if tested, the window logic would be invalid and should be guarded against or return an error.
Target consecutive blocks already exist at the very beginning of the string
How to Handle:
The first window evaluation will record 0 recolors, and subsequent windows will only yield equal or greater white counts.
Target consecutive blocks exist only at the very end of the string
How to Handle:
The sliding window will naturally traverse the entire array and capture the minimum white count when it reaches the final indices.
0/5 completed