304 North Cardinal St.
Dorchester Center, MA 02124

# Duplicate Zeros LeetCode Solution

## Problem – Duplicate Zeros LeetCode Solution

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`

### Duplicate Zeros LeetCode Solution in Python

``````    def duplicateZeros(self, A):
A[:] = [x for a in A for x in ([a] if a else [0, 0])][:len(A)]
``````

### Duplicate Zeros LeetCode Solution in C++

``````    void duplicateZeros(vector<int>& A) {
int n = A.size(), j = n + count(A.begin(), A.end(), 0);
for (int i = n - 1; i >= 0; --i) {
if (--j < n)
A[j] = A[i];
if (A[i] == 0 && --j < n)
A[j] = 0;
}
}
``````

### Duplicate Zeros LeetCode Solution in Java

``````    public void duplicateZeros(int[] arr) {
int countZero = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) countZero++;
}
int len = arr.length + countZero;
//We just need O(1) space if we scan from back
//i point to the original array, j point to the new location
for (int i = arr.length - 1, j = len - 1; i < j; i--, j--) {
if (arr[i] != 0) {
if (j < arr.length) arr[j] = arr[i];
} else {
if (j < arr.length) arr[j] = arr[i];
j--;
if (j < arr.length) arr[j] = arr[i]; //copy twice when hit '0'
}
}
}
``````
##### Duplicate Zeros LeetCode Solution Review:

In our experience, we suggest you solve this Duplicate Zeros LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Duplicate Zeros LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Duplicate Zeros LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions