Minimum Recolors to Get K Consecutive Black Blocks — LeetCode 2379 Python Solution

EasyStringSliding Window
Problem
#2379
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def minimumRecolors(self, blocks: str, k: int) -> int:
        ans = cnt = blocks[:k].count('W')
        for i in range(k, len(blocks)):
            cnt += blocks[i] == 'W'
            cnt -= blocks[i - k] == 'W'
            ans = min(ans, cnt)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string blocks
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks?
LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks is rated Easy on LeetCode.
What is the time complexity of LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks?
The Python solution on this page runs in O(n), where n is the length of the string blocks.
What is the space complexity of LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks cover?
LeetCode 2379. Minimum Recolors to Get K Consecutive Black Blocks is tagged String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview