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:

  1. Initialize two variables: count and maxCount. count will keep track of the current count of 1s, and maxCount will store the maximum count seen so far.
  2. 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 count to 1 (because we found a new group of 1s).
  3. Update maxCount with the maximum value seen so far.
  4. Calculate the minimum number of swaps required by subtracting count from maxCount. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.