Skip to content

Commit 478db26

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 18 MB (20.22%)
1 parent 72128f9 commit 478db26

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given a <strong>0-indexed</strong> string <code>blocks</code> of length <code>n</code>, where <code>blocks[i]</code> is either <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>, representing the color of the <code>i<sup>th</sup></code> block. The characters <code>&#39;W&#39;</code> and <code>&#39;B&#39;</code> denote the colors white and black, respectively.</p>
2+
3+
<p>You are also given an integer <code>k</code>, which is the desired number of <strong>consecutive</strong> black blocks.</p>
4+
5+
<p>In one operation, you can <strong>recolor</strong> a white block such that it becomes a black block.</p>
6+
7+
<p>Return<em> the <strong>minimum</strong> number of operations needed such that there is at least <strong>one</strong> occurrence of </em><code>k</code><em> consecutive black blocks.</em></p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> blocks = &quot;WBBWWBBWBW&quot;, k = 7
14+
<strong>Output:</strong> 3
15+
<strong>Explanation:</strong>
16+
One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks
17+
so that blocks = &quot;BBBBBBBWBW&quot;.
18+
It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.
19+
Therefore, we return 3.
20+
</pre>
21+
22+
<p><strong class="example">Example 2:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> blocks = &quot;WBWBBBW&quot;, k = 2
26+
<strong>Output:</strong> 0
27+
<strong>Explanation:</strong>
28+
No changes need to be made, since 2 consecutive black blocks already exist.
29+
Therefore, we return 0.
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>n == blocks.length</code></li>
37+
<li><code>1 &lt;= n &lt;= 100</code></li>
38+
<li><code>blocks[i]</code> is either <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li>
39+
<li><code>1 &lt;= k &lt;= n</code></li>
40+
</ul>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Approach: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def minimumRecolors(self, blocks: str, k: int) -> int:
8+
curr_white = blocks[:k].count('W')
9+
10+
min_operations = curr_white
11+
12+
for i in range(k, len(blocks)):
13+
# Remove the contribution of the leftmost character
14+
if blocks[i - k] == 'W':
15+
curr_white -= 1
16+
17+
if blocks[i] == 'W':
18+
curr_white += 1
19+
20+
min_operations = min(min_operations, curr_white)
21+
22+
return min_operations
23+

0 commit comments

Comments
 (0)