1089. Duplicate Zeros LeetCode Solution

In this guide, you will get 1089. Duplicate Zeros LeetCode Solution with the best time and space complexity. The solution to Duplicate Zeros problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Duplicate Zeros solution in C++
  4. Duplicate Zeros solution in Java
  5. Duplicate Zeros solution in Python
  6. Additional Resources
1089. Duplicate Zeros LeetCode Solution image

Problem Statement of Duplicate Zeros

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Example 1:

Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: arr = [1,2,3]
Output: [1,2,3]
Explanation: After calling your function, the input array is modified to: [1,2,3]

Constraints:

1 <= arr.length <= 104
0 <= arr[i] <= 9

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1089. Duplicate Zeros LeetCode Solution in C++

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];
    }
  }
};
/* code provided by PROGIEZ */

1089. Duplicate Zeros LeetCode Solution in Java

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];
    }
  }
}
// code provided by PROGIEZ

1089. Duplicate Zeros LeetCode Solution in Python

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
# code by PROGIEZ

Additional Resources

See also  420. Strong Password Checker LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.