Duplicate Zeros

This problem asks us to duplicate each occurrence of zero in the array, shifting the remaining elements to the right. The elements beyond the length of the original array are not written. The modifications are done to the input array in place.

A good approach to solve this problem is to use two pointers. The first pointer is to iterate the array from left to right. The second pointer is to count the new length after duplicating zeros. After counting, we use the two pointers to iterate the array from right to left and move elements to their new position.

Here’s the Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        n = len(arr)
        zeros = arr.count(0)
        i = n - 1
        j = n + zeros - 1

        while i != j:
            if arr[i] != 0:
                if j < n:
                    arr[j] = arr[i]
                j -= 1
            else:
                if j < n:
                    arr[j] = arr[i]
                j -= 1
                if j < n:
                    arr[j] = arr[i]
                j -= 1
            i -= 1

In this code, n is the length of the array, zeros is the number of zeros in the array, i is the pointer to iterate the array from right to left, and j is the pointer to count the new length. In the while loop, if the current element arr[i] is not zero, we just copy it to its new position if it’s in the array. If the current element is zero, we copy it twice to its new position if it’s in the array. After moving elements, we decrease the pointers i and j. This loop continues until i and j meet.