703334. Min Swaps to Group 1s
Medium
Min Swaps to Group 1s
Slug: minimum-swaps-required-to-group-all-1s-together2451
Difficulty: Medium
Id: 703334
Topic Tags: Arrays, Data Structures
Company Tags: Adobe
Summary
Given an array of binary values (0s and 1s), find the minimum number of swaps required to group all the 1s together in the array. The goal is to minimize the number of operations by moving the 1s as close as possible.
Detailed Explanation
The problem involves finding the minimum number of swaps required to group all the 1s together in an array. To solve this, we can use a greedy approach.
Here's a step-by-step breakdown:
- Initialize two variables:
countandmaxCount.countwill keep track of the current count of 1s, andmaxCountwill store the maximum count seen so far. - Iterate through the array from left to right. For each element:
- If the element is a 1, increment
count. - If the element is a 0, reset
countto 1 (because we found a new group of 1s).
- If the element is a 1, increment
- Update
maxCountwith the maximum value seen so far. - Calculate the minimum number of swaps required by subtracting
countfrommaxCount. This represents the difference between the size of the largest group and the current group.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a constant amount of space to store the variables.
Here's an ASCII art diagram representing the process:
[0, 1, 0, 1, 1, 0, 1]
^ ^
| Group 1 |
v v
[0, 1, 0, 1, 1, 1, 0] -> [0, 1, 0, 1, 1, 1, 1]
Optimized Solutions
Java
public int minSwaps(int[] arr) {
int count = 0;
int maxCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) {
count++;
} else {
count = 1;
}
maxCount = Math.max(maxCount, count);
}
return maxCount - count;
}