Minimum Swaps to Group All 1's Together Problem
Description
LeetCode Problem 1151.
Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.
Example 1:
Input: data = [1,0,1,0,1]
Output: 1
Explanation: There are 3 ways to group all 1's together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.
Example 2:
Input: data = [0,0,0,1,0]
Output: 0
Explanation: Since there is only one 1 in the array, no swaps are needed.
Example 3:
Input: data = [1,0,1,0,1,0,0,1,1,0,1]
Output: 3
Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
Constraints:
1 <= data.length <= 10^5data[i]is either0or1.
Solution
Approach: Sliding Window of Length k
Let k be the number of 1s in data. Once they are grouped, they fill some window of exactly k consecutive positions. For a fixed window, every 0 inside it must be swapped out with a 1 from outside it. There are exactly as many 0s inside as 1s outside, and one swap fixes one of each, so the window costs k - (number of 1s already inside) swaps.
So we want the window of length k that already contains the most 1s. Slide a window of length k across the array, keeping a running count: when it moves one step right, add the element that enters and subtract the one that leaves. The answer is k - best.
If there are no 1s at all (k = 0), nothing needs to move and the answer is 0.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minSwaps(self, data: List[int]) -> int:
k = sum(data) # the 1s end up in some window of length k
ones = sum(data[:k]) # 1s inside the current window
best = ones
for i in range(k, len(data)):
ones += data[i] - data[i - k] # slide the window one step right
best = max(best, ones)
# Each 0 inside the best window is swapped with a 1 from outside it.
return k - best