Minimum Recolors to Get K Consecutive Black Blocks — LeetCode 2379 Python Solution
- Problem
- #2379
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string blocks |
| Space | O(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.