Duplicate Zeros - Problem
Transform an array by duplicating zeros!
You're given a fixed-length integer array
Important: You must modify the input array in-place without returning anything.
Example:
Notice how the original zeros at indices 1, 4, and 7 each get duplicated, pushing subsequent elements right until they fall off the end.
You're given a fixed-length integer array
arr. Your task is to duplicate each occurrence of zero, shifting all remaining elements to the right. Here's the catch: the array size stays the same, so elements that get pushed beyond the original length are discarded.Important: You must modify the input array in-place without returning anything.
Example:
[1,0,2,3,0,4,5,0] becomes [1,0,0,2,3,0,0,4]Notice how the original zeros at indices 1, 4, and 7 each get duplicated, pushing subsequent elements right until they fall off the end.
Input & Output
example_1.py โ Basic Case
$
Input:
[1,0,2,3,0,4,5,0]
โบ
Output:
[1,0,0,2,3,0,0,4]
๐ก Note:
The zeros at indices 1, 4, and 7 are duplicated. The first zero creates [1,0,0,2,3,0,4,5], the second zero creates [1,0,0,2,3,0,0,4,5], and since we exceed the array length, the 5 is dropped. The final zero would create another duplicate but it falls outside the array bounds.
example_2.py โ Edge Case with Consecutive Zeros
$
Input:
[1,0,0,1]
โบ
Output:
[1,0,0,0]
๐ก Note:
The first zero at index 1 gets duplicated, shifting everything right: [1,0,0,0,1]. The second original zero would also get duplicated, but there's no space left in the array, so the final result is [1,0,0,0] with the trailing elements dropped.
example_3.py โ No Zeros
$
Input:
[1,2,3,4]
โบ
Output:
[1,2,3,4]
๐ก Note:
Since there are no zeros in the array, no duplication occurs and the array remains unchanged.
Constraints
- 1 โค arr.length โค 104
- 0 โค arr[i] โค 9
- You must modify the array in-place
- Do not return anything from your function
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Belt
First, count how many zeros exist to predict the final layout
2
Work Backwards
Start from the end and work backwards to avoid disturbing items you haven't processed yet
3
Duplicate Zeros
When you encounter a zero, place two zeros in the final positions
4
Handle Overflow
Items that would exceed the belt length naturally fall off
Key Takeaway
๐ฏ Key Insight: Working backwards with pre-calculated positions ensures optimal O(n) performance while safely handling in-place modifications without data corruption.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code