Duplicate every zero in an array in place while keeping the array length fixed.
Problem
Given a fixed-length integer array, duplicate each occurrence of 0 by shifting the remaining elements to the right. Elements that fall off the end of the array are discarded.
You must modify the array in place. The final array must keep the same length as the input.
Goal
Return the array after all zeros have been duplicated and all other elements shifted accordingly.
Input Format
- An integer array
arrof fixed length. - You may assume the array can be modified in place.
Output Format
- The same array after duplicating each
0and shifting elements right. - The returned/modified array must have the original length.
Constraints
- The array length is fixed.
- Duplicate zeros in place.
- Elements shifted beyond the end are discarded.
- Preserve the relative order of the remaining elements.
Example 1
Input
arr = [1,0,2,3,0,4,5,0]
Output
[1,0,0,2,3,0,0,4]
Explanation
Each zero is duplicated, and elements that would move past the end are dropped.
Example 2
Input
arr = [1,2,3]
Output
[1,2,3]
Explanation
There are no zeros to duplicate.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.