Build the logical expanded sequence only up to the original length, then copy it back so the input is modified in place as required.
Complexity
O(n) time and O(n) auxiliary space.
Duplicate each zero in a fixed-length array while shifting later values and discarding overflow.
Build the logical expanded sequence only up to the original length, then copy it back so the input is modified in place as required.
O(n) time and O(n) auxiliary space.
package main
func duplicateZeros(arr []int) {
expanded := make([]int, 0, len(arr))
for _, value := range arr {
if len(expanded) == len(arr) {
break
}
expanded = append(expanded, value)
if value == 0 && len(expanded) < len(arr) {
expanded = append(expanded, 0)
}
}
copy(arr, expanded)
}
class Solution:
def duplicateZeros(self, arr: list[int]) -> None:
expanded: list[int] = []
for value in arr:
if len(expanded) == len(arr): break
expanded.append(value)
if value == 0 and len(expanded) < len(arr): expanded.append(0)
arr[:] = expanded
function duplicateZeros(arr: number[]): void {
const expanded: number[] = [];
for (const value of arr) { if (expanded.length === arr.length) break; expanded.push(value); if (value === 0 && expanded.length < arr.length) expanded.push(0); }
for (let index = 0; index < arr.length; index += 1) arr[index] = expanded[index];
}