#2379

Minimum Recolors to Get K Consecutive Black Blocks

Easy
StringSliding WindowSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to efficiently count the number of white blocks in a window of size k. This avoids the need to recount for overlapping parts of the string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to count the number of white blocks in the first window of size k.
  2. 2Step 2: Slide the window across the string, updating the count by removing the block that goes out of the window and adding the new block that comes into the window.
  3. 3Step 3: Keep track of the minimum recolors needed as you slide the window.
solution.py14 lines
1def minimumRecolors(blocks, k):
2    min_recolors = 0
3    n = len(blocks)
4    for i in range(k):
5        if blocks[i] == 'W':
6            min_recolors += 1
7    current_recolors = min_recolors
8    for i in range(k, n):
9        if blocks[i] == 'W':
10            current_recolors += 1
11        if blocks[i - k] == 'W':
12            current_recolors -= 1
13        min_recolors = min(min_recolors, current_recolors)
14    return min_recolors

Complexity note: This complexity is achieved because we only traverse the string once, maintaining a count of white blocks in the current window without needing nested loops.

  • 1Using a sliding window reduces the number of operations needed to count the recolors.
  • 2Maintaining a running count of changes avoids redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.