Duplicate Zeros (LeetCode 1089): Solution and Explanation
You get a fixed-length array. Write every zero twice, shifting the later elements right, and drop whatever is pushed past the end. The change happens in place.
Intuition
The obvious way is to scan left to right and, at each zero, shift the rest of the array one place right. That is correct but costs O(n) per zero, so it is O(n^2) on an array full of zeros.
Think about where each element ends up instead. If there are zeros zeros, the fully expanded array would be n + zeros long. An element's slot in that longer array is its index plus the number of zeros before it. The real array is just the first n slots of it.
Filling from the back is safe because the write position is never left of the read position. Every value you overwrite has already been read, so nothing is lost. Values whose slot is n or more are exactly the ones that fall off the end, so you simply skip writing them.
Approach: Count zeros, then two pointers from the back
- Count the zeros in
arr. - Set the read pointer
i = n - 1and the write pointerj = n + zeros - 1on the imaginary longer array. - While
i >= 0, writearr[i]into slotjifj < n. - If
arr[i]is 0, movejleft once more and write a second 0 there ifj < n. - Move both
iandjone step left and repeat.
Step-by-step example
arr = [1,0,2,3,0,4,5,0]
- There are 3 zeros, so the expanded array would have 11 slots: i = 7 and j = 10.
- arr[7] = 0 belongs at slots 10 and 9. Both are past the end (n = 8), so both copies are dropped.
- arr[6] = 5 belongs at slot 8, also past the end, so it is dropped. arr[5] = 4 lands in slot 7.
- arr[4] = 0 lands in slots 6 and 5. arr[3] = 3 goes to slot 4 and arr[2] = 2 to slot 3.
- arr[1] = 0 lands in slots 2 and 1. Now j = i = 0, so arr[0] = 1 stays put. The result is [1,0,0,2,3,0,0,4].
Code: Python, Java, C++
1class Solution:
2 def duplicateZeros(self, arr: List[int]) -> None:
3 n = len(arr)
4 zeros = arr.count(0)
5 i, j = n - 1, n + zeros - 1
6 while i >= 0:
7 if j < n:
8 arr[j] = arr[i]
9 if arr[i] == 0:
10 j -= 1
11 if j < n:
12 arr[j] = 0
13 i -= 1
14 j -= 11class Solution {
2 public void duplicateZeros(int[] arr) {
3 int n = arr.length;
4 int zeros = 0;
5 for (int x : arr) {
6 if (x == 0) zeros++;
7 }
8 int i = n - 1, j = n + zeros - 1;
9 while (i >= 0) {
10 if (j < n) {
11 arr[j] = arr[i];
12 }
13 if (arr[i] == 0) {
14 j--;
15 if (j < n) {
16 arr[j] = 0;
17 }
18 }
19 i--;
20 j--;
21 }
22 }
23}1class Solution {
2public:
3 void duplicateZeros(vector<int>& arr) {
4 int n = arr.size();
5 int zeros = count(arr.begin(), arr.end(), 0);
6 int i = n - 1, j = n + zeros - 1;
7 while (i >= 0) {
8 if (j < n) {
9 arr[j] = arr[i];
10 }
11 if (arr[i] == 0) {
12 j--;
13 if (j < n) {
14 arr[j] = 0;
15 }
16 }
17 i--;
18 j--;
19 }
20 }
21};Time and space complexity
O(n)
One pass counts the zeros and one backward pass places every element, each with constant work.
O(1)
Only the zero count and two pointers are stored; the array is rewritten in place.
Other approaches
Shift on every zero (time O(n^2), space O(1))
Scan left to right. When you see a zero, move every later element one slot right and write a second zero, then skip past it. It is the most direct translation of the statement but takes O(n) per zero.
Build a copy (time O(n), space O(n))
Build a new list by appending each value, and a second 0 after each zero, stopping at length n. Then copy it back into arr. It is simple but uses O(n) extra memory.
Common mistakes
- Filling from the front. Writing a duplicated zero overwrites the next element before you have read it.
- Starting
jatn - 1. The write pointer must start atn + zeros - 1so every element keeps its offset from the zeros before it. - Writing the second zero without checking
j < n. The last zero that fits may have its copy pushed just past the end. - Returning a new array. The judge checks
arritself, so the function must modify it in place.
Frequently asked questions
Why is it safe to write from the back?
The write pointer j is always at or to the right of the read pointer i, because j - i equals the number of zeros still to the left. Every slot you overwrite has already been read.
What happens to a zero whose copy does not fit?
Its first copy lands in the last slot and its second copy would land past the end, so only one 0 is written. The check j < n before the second write handles this case.
Can the loop stop early?
Yes. Once j equals i, no zeros remain to the left, so every remaining element already sits in its final slot. Stopping there is an optimisation; continuing is harmless because each write puts a value back where it already is.