Duplicate Zeros — LeetCode 1089 Python Solution

EasyArrayTwo Pointers
Problem
#1089
Reading time
4 min

The problem

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.

Example

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]

Python solution

Python
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        n = len(arr)
        i, k = -1, 0
        while k < n:
            i += 1
            k += 1 if arr[i] else 2
        j = n - 1
        if k == n + 1:
            arr[j] = 0
            i, j = i - 1, j - 1
        while ~j:
            if arr[i] == 0:
                arr[j] = arr[j - 1] = arr[i]
                j -= 1
            else:
                arr[j] = arr[i]
            i, j = i - 1, j - 1

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1089. Duplicate Zeros is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1089. Duplicate Zeros?
LeetCode 1089. Duplicate Zeros is rated Easy on LeetCode.
What is the time complexity of LeetCode 1089. Duplicate Zeros?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 1089. Duplicate Zeros?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1089. Duplicate Zeros cover?
LeetCode 1089. Duplicate Zeros is tagged Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview