NeetCode #221LC-2379EasySliding Window
← Back to All Problems#221 · #2379 · Minimum Recolors to Get K Consecutive Black Blocks(得到 K 个黑块的最少涂色次数)
📌 Problem Statement & Constraints
You are given a string
blocks of 'W' and 'B' and an integer k. You want k consecutive black blocks; one operation recolours a white block to black. Return the minimum number of operations. Constraints: 1 <= k <= blocks.length <= 100, blocks consists of 'W' and 'B'.💡 Core Algorithmic Approaches
- Every window of length
kis a candidate; the cost of making it all black is the number of'W's inside it. - Maintain a sliding count of black blocks in the window, or equivalently of white blocks.
- The answer is
k - max(black count)over all windows of lengthk. - Alternatively, track the white count directly and take the minimum.
💻 Benchmark Python3 Implementation
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
cur = 0 # black blocks in the current window
best = float("inf")
for i, ch in enumerate(blocks):
if ch == "B":
cur += 1
if i >= k and blocks[i - k] == "B":
cur -= 1 # left the window
if i >= k - 1:
best = min(best, k - cur) # whites = k - blacks
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): a single counter.
⚠️ Interview Pitfalls & Follow-ups
- Counting white blocks and forgetting to reset: tracking black blocks makes the eviction trivial and the cost is
k - cur. - Evicting before adding: the order is add-then-evict, and the eviction index is
i - k. - Emitting before the first full window: the
i >= k - 1guard is required. - Assuming the window is always reachable: since
k <= n, at least one full window always exists.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner#225 · #487Max Consecutive Ones II
中文速览与面试要点
得到 K 个黑块的最少涂色次数
给你一个长度为 n 的下标从 0 开始的字符串 blocks,blocks[i] 要么是 W 表示第 i 块为白色,要么是 B 表示第 i 块为黑色。另给你一个整数 k,表示你希望得到的连续黑色块数目。你希望将 blocks 中的某些白色块涂成黑色,使得存在 k 个连续黑色块。请你返回最少需要涂色的次数。约束:1 ≤ blocks.length ≤ 100;blocks[i] 为 W 或 B ;1 ≤ k ≤ blocks.length。
核心要点
- 定长窗口统计白块数(标准解) :长度固定为 k 的窗口中,白块数量即为把该窗口全变黑所需的涂色次数。
- 滚动更新 :窗口右移一位,若新进入的字符是 W 则计数加一,若滑出的是 W 则计数减一。
- 取最小值 :所有长度为 k 的窗口中的最小白块数即为答案。
- 复杂度 :O(n) 时间、O(1) 空间。
常见陷阱
- 统计黑块数而非白块数 :需要涂色的是 白块 ,因此应统计窗口内的 W 数量。
- 每个窗口都重新 count :O(n · k),退化为平方级。必须滚动更新。
- 滑出字符的判断写成 blocks[i] :滑出的是 blocks[i − k] 。
- 忘记初始化第一个窗口 : blocks[:k].count("W") 必须先算,否则 best 初值无意义。
参考实现
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
whites = blocks[:k].count('W') # 第一个窗口的白块数
best = whites
for i in range(k, len(blocks)):
if blocks[i] == 'W':
whites += 1 # 新进入的白块
if blocks[i - k] == 'W':
whites -= 1 # 滑出的白块
if whites < best:
best = whites
return best