Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Sliding Window
Minimum Recolors To Get K Consecutive Black Blocks

Given a string of black and white blocks, find the minimum number of recolors needed to make some length-kk segment all black.

Acceptance 0%
Problem Statement

Problem

You are given a row of blocks represented by a string blocks, where each character is either 'B' for a black block or 'W' for a white block.

In one move, you may recolor a white block into a black block. Your goal is to choose some contiguous segment of length k and make every block in that segment black.

Return the minimum number of recolors required.

Interpretation

For any length-kk window, the number of recolors needed is exactly the number of white blocks inside that window. You need the smallest such value over all windows.

Input Format

  • blocks: a string consisting only of 'B' and 'W'
  • k: the length of the consecutive segment to make all black

Output Format

Return the minimum number of 'W' characters contained in any substring of length k.

Constraints

  • 1kblocks1 \le k \le |blocks|
  • blocks contains only 'B' and 'W'
  • Solve efficiently for large strings using a linear-time window scan.
Examples
Sample cases returned by the problem API.

Example 1

Input

blocks = "WBBWWBBWBW", k = 7

Output

3

Explanation

For the window "BBWWBBW", there are 3 white blocks, and no length-7 window has fewer than 3 whites. Recolor those 3 white blocks to make 7 consecutive black blocks.

Example 2

Input

blocks = "WBWBBBW", k = 2

Output

0

Explanation

The substring "BB" already contains 2 consecutive black blocks, so no recolors are needed.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.