LeetCode Solutions

1089. Duplicate Zeros

Time:

Space:

			

class Solution {
 public:
  void duplicateZeros(vector<int>& arr) {
    int zeros = count_if(begin(arr), end(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];
    }
  }
};
			

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];
    }
  }
}
			

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