Leetcode #1089: Duplicate Zeros
In this guide, we solve Leetcode #1089 Duplicate Zeros in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Two Pointers
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
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
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
The time complexity is O(n) (after optional sort O(n log n)). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.