Skip to content

1089. Duplicate Zeros

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  void duplicateZeros(vector<int>& arr) {
    int zeros = ranges::count_if(arr, [](int a) { return a == 0; });

    for (int i = arr.size() - 1, j = arr.size() + zeros - 1; i < j; --i, --j) {
      if (j < arr.size())
        arr[j] = arr[i];
      if (arr[i] == 0)
        if (--j < arr.size())
          arr[j] = arr[i];
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public void duplicateZeros(int[] arr) {
    int zeros = 0;

    for (int a : arr)
      if (a == 0)
        ++zeros;

    for (int i = arr.length - 1, j = arr.length + zeros - 1; i < j; --i, --j) {
      if (j < arr.length)
        arr[j] = arr[i];
      if (arr[i] == 0)
        if (--j < arr.length)
          arr[j] = arr[i];
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def duplicateZeros(self, arr: list[int]) -> None:
    zeros = arr.count(0)
    i = len(arr) - 1
    j = len(arr) + zeros - 1

    while i < j:
      if j < len(arr):
        arr[j] = arr[i]
      if arr[i] == 0:
        j -= 1
        if j < len(arr):
          arr[j] = arr[i]
      i -= 1
      j -= 1