Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 8, 2025 22:14
Show Gist options
  • Save Ifihan/e3371d8b0e8b0fbacea0c490adb4b4ea to your computer and use it in GitHub Desktop.
Save Ifihan/e3371d8b0e8b0fbacea0c490adb4b4ea to your computer and use it in GitHub Desktop.
Minimum Recolors to Get K Consecutive Black Blocks

Question

Approach

I use the sliding window technique to find the minimum number of white blocks ('W') that need to be changed in any substring of length k.

I then iterate through all possible windows of size k in the string and count the number of 'W' characters, keeping track of the minimum count.

Implementation

class Solution:
    def minimumRecolors(self, blocks: str, k: int) -> int:
        min_operations = float('inf')
        
        for i in range(len(blocks) - k + 1):
            window = blocks[i:i + k]
            operations = window.count('W')
            min_operations = min(min_operations, operations)
        
        return min_operations

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment