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.length1 <= n <= 100blocks[i] is either 'W' or 'B'.1 <= k <= nThe Sliding Window Approach keeps track of a dynamic set of elements (window) and updates the count of 'W' blocks for each position of the window. It enables the solution to efficiently calculate the minimum number of recolors needed for k consecutive 'B' blocks.
The C solution uses a sliding window of size k over the string 'blocks'. It first sets up an initial count of white blocks ('W') in the first window. As the window slides, for each new block entering the window and for each old block leaving, it adjusts the count of white blocks. The solution tracks the minimum count of 'W' found in any window.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(1)
The Prefix Sum with Optimization approach calculates the number of 'W' blocks in each possible window using precomputed cumulative sums. By calculating differences between prefix sums at appropriate indices, it allows for efficient queries of any window, achieving the solution in linear time.
This C solution calculates a prefix sum of white blocks ('W') to allow for quick query over any subsequence of the array. The prefix sums help in efficiently calculating the number of 'W' blocks in a given window.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Sliding Window Approach | Time Complexity: O(n), Space Complexity: O(1) |
| Prefix Sum with Optimization | Time Complexity: O(n), Space Complexity: O(n) |
Minimum Recolors to Get K Consecutive Black Blocks - Leetcode 2379 • NeetCodeIO • 5,510 views views
Watch 9 more video solutions →Practice Minimum Recolors to Get K Consecutive Black Blocks with our built-in code editor and test cases.
Practice on FleetCode