File: minimum-recolors-to-get-k-consecutive-black-blocks/solution.py

Date: 2026-06-06

Time: 18:00

Purpose

This file solves LeetCode 2379: Minimum Recolors to Get K Consecutive Black Blocks. Given a string of 'W' (white) and 'B' (black) characters, it finds the minimum number of white blocks you'd need to repaint black to create a contiguous run of k black blocks.

It owns exactly one responsibility: the min_operations function.

Key Components

min_operations(blocks: str, k: int) -> int

Contract: Given a string blocks containing only 'W' and 'B', and an integer k where 1 <= k <= len(blocks), returns the minimum number of recolors (white-to-black) needed to produce k consecutive black blocks.

Patterns

Fixed-size sliding window. This is the textbook application: maintain a count over a window of size k, slide it one position at a time, and track the minimum.

The implementation avoids recomputing the count from scratch each step. Instead, it updates incrementally by adding the incoming element and removing the outgoing one. The expression (blocks[i] == "W") - (blocks[i - k] == "W") exploits Python's bool-to-int coercion — True becomes 1, False becomes 0 — to do the add/remove in a single arithmetic statement.

Dependencies

Imports: None. Pure standard Python.

Imported by: The test_solution.py in the same directory. The "Imported By" list in the prompt is misleading — those are all unrelated test files for other problems, likely an artifact of the indexing tool matching on a shared test harness pattern, not actual imports of this module.

Flow

1. Initialize window (line 14): Count 'W's in blocks[0:k] using str.count. This is the cost of making the *first* window all-black.

2. Set baseline (line 15): minops = whitecount.

3. Slide (lines 18–19): For each position i from k to len(blocks) - 1:

4. Return min_ops.

Invariants

Error Handling

None. The function trusts its inputs match the LeetCode constraints. If k > len(blocks), blocks[:k].count("W") still works (counts over the full string), but the loop body never executes, so you'd get the count of 'W's in the entire string — which would be a valid but semantically wrong answer for an invalid input. No validation is performed; this is typical for LeetCode solutions.

Topics to Explore

Beliefs