![]() |
VOOZH | about |
Given an array of 0's and 1's, we need to find the minimum swaps required to group all 1's present in the array together. In a swap operation, we swap two elements at different indexes.
Examples:
Input: arr[] = [1, 0, 1, 0, 1]
Output: 1
Explanation: Only 1 swap is required to group all 1's together. Swapping index 1 with 4 will give arr[] = [1, 1, 1, 0, 0]
Input: arr[] = [1, 1, 0, 1, 0, 1, 1]
Output: 2
Explanation: Only 2 swap is required to group all 1's together. Swapping index 0 with 2 and 1 with 4 will give arr[] = [0, 0, 1, 1, 1, 1, 1]Input: arr[] = [0, 0, 0]
Output: -1
Explanation: No 1s are present in the array, so return -1.
Table of Content
The idea is based on the fact that a subarray with more 1s would require less swaps.
1
This is mainly an optimization over the above approach. Count the total number of 1s (
x) in the array, then find a subarray of lengthxwith the maximum 1s using a sliding count. Track the maximum 1s in any such subarray and returnx - maxOnesas the minimum swaps needed.
1