Duplicate Zeros Problem
Description
LeetCode Problem 1089.
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 <= 10^40 <= arr[i] <= 9
Solution
Approach: Two Passes with Two Pointers
Copying from left to right overwrites values before we read them. Copying from right to left avoids that, but we first need to know which element ends up last.
Pass 1. Walk from the left with a source index i and the length k that the output would have so far: add 1 for a non-zero value and 2 for a zero. Stop as soon as k >= n. Now arr[i] is the last element that is kept.
Pass 2. Write from the right with j = n - 1, moving i backwards: copy arr[i] to arr[j], and if it is a zero, write a second zero at j - 1. Since j never falls behind i, nothing is overwritten before it is read.
The tricky case is when the last kept element is a zero that only has room for one copy (k == n + 1), as in [1,2,0]: its second copy would fall outside the array. Write a single 0 at the end, then move both i and j back by one before pass 2.
Complexity: O(n) time and O(1) extra space.
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n = len(arr)
# Find the last element i that still fits; k is the length written so far.
i, k = -1, 0
while k < n:
i += 1
k += 1 if arr[i] else 2
j = n - 1 # write position, filling from the right
if k == n + 1: # the last kept zero has room for only one copy
arr[j] = 0
i, j = i - 1, j - 1
while j >= 0:
arr[j] = arr[i]
if arr[i] == 0:
j -= 1
arr[j] = 0
i, j = i - 1, j - 1