The naive solution would involve iterating through all possible subarrays of length ones
(the number of 1s in the array) and counting the number of 0s in each subarray. The minimum number of 0s would then be the answer, as each 0 would need to be swapped out. This approach would have a time complexity of O(n^2), where n is the length of the array, due to the nested loops required to iterate through all possible subarrays.
A more efficient solution can be achieved using a sliding window approach. First, count the total number of 1s in the array. This represents the size of our window. Then, iterate through the array using a sliding window of that size, counting the number of 0s within each window. The minimum number of 0s encountered is the answer.
def min_swaps(nums):
ones = sum(nums)
n = len(nums)
if ones == 0 or ones == n:
return 0
min_zeros = float('inf')
for i in range(n):
zeros = 0
for j in range(ones):
if nums[(i + j) % n] == 0:
zeros += 1
min_zeros = min(min_zeros, zeros)
return min_zeros
# Example Usage
nums1 = [0,1,0,1,1,0,0]
print(f"Input: {nums1}, Output: {min_swaps(nums1)}") # Output: 1
nums2 = [0,1,1,1,0,0,1,1,0]
print(f"Input: {nums2}, Output: {min_swaps(nums2)}") # Output: 2
nums3 = [1,1,0,0,1]
print(f"Input: {nums3}, Output: {min_swaps(nums3)}") # Output: 0
class Solution {
public int minSwaps(int[] nums) {
int ones = 0;
int n = nums.length;
for (int num : nums) {
ones += num;
}
if (ones == 0 || ones == n) {
return 0;
}
int minZeros = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int zeros = 0;
for (int j = 0; j < ones; j++) {
if (nums[(i + j) % n] == 0) {
zeros++;
}
}
minZeros = Math.min(minZeros, zeros);
}
return minZeros;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = {0, 1, 0, 1, 1, 0, 0};
System.out.println("Input: [0,1,0,1,1,0,0], Output: " + sol.minSwaps(nums1)); // Output: 1
int[] nums2 = {0, 1, 1, 1, 0, 0, 1, 1, 0};
System.out.println("Input: [0,1,1,1,0,0,1,1,0], Output: " + sol.minSwaps(nums2)); // Output: 2
int[] nums3 = {1, 1, 0, 0, 1};
System.out.println("Input: [1,1,0,0,1], Output: " + sol.minSwaps(nums3)); // Output: 0
}
}
The optimal solution has a time complexity of O(n), where n is the length of the array. The outer loop iterates through the array once, and the inner loop iterates ones
times (where ones
is the number of 1s in the array). In the worst case, ones
could be equal to n
, making the inner loop also O(n). Thus the dominant factor is the outer loop, making the overall time complexity O(n).
The space complexity of the optimal solution is O(1), constant space. We only use a few extra variables to store the count of ones and the minimum number of zeros, regardless of the input array size.
min_zeros
(infinity) will be returned. However, it's good practice to explicitly check for this and return 0.if ones == 0 or ones == n: return 0
.%
when accessing array elements within the sliding window, ensuring that the window wraps around the array.