LeetCode Entry

2379. Minimum Recolors to Get K Consecutive Black Blocks

08.03.2025 easy 2025 kotlin rust

Min 'W' flips to make k 'B' window

2379. Minimum Recolors to Get K Consecutive Black Blocks easy blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/919

Problem TLDR

Min ‘W’ flips to make k ‘B’ #medium #sliding_window

Intuition

The brute-force is accepted: count ‘W’ in k-length slice from every index.

Another solution is a sliding window: move k-length window and count ‘W’.

Approach

  • the best way to not make one-off mistake is to avoid pointes at all

Complexity

  • Time complexity: \(O(n^2)\), or O(n)

  • Space complexity: \(O(n)\), or O(1)

Code


    fun minimumRecolors(blocks: String, k: Int) =
        blocks.windowed(k).minOf { it.count { it > 'B' }}


    pub fn minimum_recolors(blocks: String, k: i32) -> i32 {
        let (s, mut w, k) =  (blocks.as_bytes(), 0, k as usize);
        (0..s.len()).map(|r| {
            if s[r] > b'B' { w += 1 }
            if r + 1 < k { 100 } else
            if s[r + 1 - k] > b'B' { w -= 1; w + 1 } else { w }
        }).min().unwrap()
    }


    int minimumRecolors(string b, int k, int res = 100, int w = 0) {
        for (int r = 0; r < size(b); w -= ++r >= k && b[r - k] > 'B')
            w += b[r] > 'B', res = min(res, r < k - 1 ? 100 : w);
        return res;
    }