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. The array’s length should stay the same after modifying the input.
Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
To solve this problem in-place, we’ll adopt a two-pass approach:
This strategy ensures that we correctly duplicate zeros within the array length constraints.
i
of the original array whose value will remain within bounds after duplications.def duplicateZeros(arr):
n = len(arr)
zeros = 0
# First pass: count zeros till the effective end
for i in range(n):
if i + zeros >= n:
break
if arr[i] == 0:
# Check if zero can't be duplicated because it would exceed length
if i + zeros == n - 1:
arr[n - 1] = 0 # edge case: single zero making end of array
n -= 1
break
zeros += 1
# Second pass: start from the end and duplicate zeros while shifting elements
for i in range(n - 1, -1, -1):
if i + zeros < len(arr):
arr[i + zeros] = arr[i]
if arr[i] == 0:
zeros -= 1
if i + zeros < len(arr):
arr[i + zeros] = 0
# Example usage
arr = [1,0,2,3,0,4,5,0]
duplicateZeros(arr)
print(arr) # Output should be [1,0,0,2,3,0,0,4]
The time complexity of the solution is O(n), where n is the length of the array. This is because we are performing a linear scan to count zeros and another linear scan to shift elements and duplicate zeros.
The space complexity is O(1), as we are modifying the array in-place without using any additional data structures that depend on the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?