Skip to main content
Back to problems
#2379
Easy Algorithms

Minimum recolors to get k consecutive black blocks

String Sliding Window
68.6% acceptance
Feb 25, 2026
1313
38
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_recolors(blocks: String, k: i32) -> i32 {
    let k = k as usize;
    let b: Vec<i32> = blocks.bytes().map(|c| if c == b'W' { 1 } else { 0 }).collect();
    let mut whites: i32 = b[..k].iter().sum();
    let mut min_ops = whites;
    for i in k..b.len() {
      whites += b[i] - b[i - k];
      min_ops = min_ops.min(whites);
    }
    min_ops
  }
}