1089. Duplicate Zeros
Description
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 <= 1040 <= arr[i] <= 9
Solutions
Solution 1: Two Pointers
Thinking
Each zero must be duplicated in place and the tail truncated. An extra array is not in-place. Writing from the left overwrites unread values, so we first find the last original index that still fits, then fill from the right.
\(i\) and a virtual length \(k\) advance together: \(+1\) for a nonzero, \(+2\) for a zero, until \(k\ge n\). If a final zero makes \(k=n+1\), that zero is written once at the end.
Then \(j\) walks from \(n-1\): a zero occupies two slots, a nonzero one.
Scan from left to right to see how far the original array can go after zeros are duplicated. Pointer \(i\) is the last source index that still fits, and \(k\) is the virtual length after duplication: add \(1\) for a nonzero value and \(2\) for a zero. Stop when \(k \ge n\).
Let \(j = n - 1\) be the write index. If the last kept value is a zero that would overflow (\(k = n + 1\)), write that single zero at \(arr[j]\) and decrement both \(i\) and \(j\).
Then fill from right to left. Copy \(arr[i]\) once into \(arr[j]\) if it is nonzero, or twice if it is zero.
The time complexity is \(O(n)\) and the space complexity is \(O(1)\), where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |