Skip to content

Commit 87527b5

Browse files
committed
Sync LeetCode submission Runtime - 103 ms (16.82%), Memory - 21.7 MB (88.86%)
1 parent 474d0cb commit 87527b5

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Given a&nbsp;binary array <code>data</code>, return&nbsp;the minimum number of swaps required to group all <code>1</code>&rsquo;s present in the array together in <strong>any place</strong> in the array.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> data = [1,0,1,0,1]
8+
<strong>Output:</strong> 1
9+
<strong>Explanation:</strong> There are 3 ways to group all 1&#39;s together:
10+
[1,1,1,0,0] using 1 swap.
11+
[0,1,1,1,0] using 2 swaps.
12+
[0,0,1,1,1] using 1 swap.
13+
The minimum is 1.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> data = [0,0,0,1,0]
20+
<strong>Output:</strong> 0
21+
<strong>Explanation:</strong> Since there is only one 1 in the array, no swaps are needed.
22+
</pre>
23+
24+
<p><strong class="example">Example 3:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> data = [1,0,1,0,1,0,0,1,1,0,1]
28+
<strong>Output:</strong> 3
29+
<strong>Explanation:</strong> One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= data.length &lt;= 10<sup>5</sup></code></li>
37+
<li><code>data[i]</code> is either <code>0</code> or <code>1</code>.</li>
38+
</ul>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Approach 1: Sliding Window with Two Pointers
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def minSwaps(self, data: List[int]) -> int:
8+
ones = sum(data)
9+
count_ones = max_ones = 0
10+
left = right = 0
11+
12+
while right < len(data):
13+
# updating the number of 1's by adding the new element
14+
count_ones += data[right]
15+
right += 1
16+
17+
# maintain the length of the window to ones
18+
if right - left > ones:
19+
# Remove oldest element
20+
count_ones -= data[left]
21+
left += 1
22+
23+
max_ones = max(max_ones, count_ones)
24+
25+
return ones - max_ones
26+
27+

0 commit comments

Comments
 (0)