Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2379: Minimum Recolors to Get K Consecutive Black Blocks

In this guide, we solve Leetcode #2379 Minimum Recolors to Get K Consecutive Black Blocks in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: String, Sliding Window

Intuition

We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.

Expanding and shrinking the window lets us maintain validity without restarting the scan.

Approach

Grow the window with a right pointer, and shrink from the left only when the constraint is violated.

Track the best window as you go to keep the solution linear.

Steps:

  • Expand the right end of the window.
  • While invalid, move the left end to restore constraints.
  • Update the best window found.

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 so that blocks = "BBBBBBBWBW". It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations. Therefore, we return 3.

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 ans

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the string blocksblocksblocks. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy