Skip to content

1151. Minimum Swaps to Group All 1's Together 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int minSwaps(vector<int>& data) {
    const int k = ranges::count(data, 1);
    int ones = 0;     // the number of ones in the window
    int maxOnes = 0;  // the maximum number of ones in the window

    for (int i = 0; i < data.size(); ++i) {
      if (i >= k && data[i - k])
        --ones;
      if (data[i])
        ++ones;
      maxOnes = max(maxOnes, ones);
    }

    return k - maxOnes;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minSwaps(int[] data) {
    final int k = (int) Arrays.stream(data).filter(a -> a == 1).count();
    int ones = 1;    // the number of ones in the window
    int maxOnes = 0; // the maximum number of ones in the window

    for (int i = 0; i < data.length; ++i) {
      if (i >= k && data[i - k] == 1)
        --ones;
      if (data[i] == 1)
        ++ones;
      maxOnes = Math.max(maxOnes, ones);
    }

    return k - maxOnes;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def minSwaps(self, data: List[int]) -> int:
    k = data.count(1)
    ones = 0  # the number of ones in the window
    maxOnes = 0  # the maximum number of ones in the window

    for i, num in enumerate(data):
      if i >= k and data[i - k]:
        ones -= 1
      if num:
        ones += 1
      maxOnes = max(maxOnes, ones)

    return k - maxOnes