31. Zero Doubler
A photocopier is loaded with a strip of exactly n numbered slots. A special mode copies the strip, but every slot that holds a 0 is printed twice, which pushes everything after it one place to the right. Anything pushed beyond the end of the strip is cut off, so the printed strip still has exactly n slots.
Write a method duplicateZeros that takes the array nums and returns the printed strip: the array after each 0 has been doubled and the result truncated to the original length. Non-zero values are copied once.
Example 1
- Input:
- nums = [1,0,2,3,0,4,5,0]
- Output:
- [1,0,0,2,3,0,0,4]
- Explanation:
Each 0 is doubled: 1, 0, 0, 2, 3, 0, 0, 4, 5, 0, 0. Keeping only the first 8 values gives [1, 0, 0, 2, 3, 0, 0, 4].
Example 2
- Input:
- nums = [1,2,3]
- Output:
- [1,2,3]
- Explanation:
There are no zeros, so the strip is unchanged.
Constraints
1 ≤ nums.length ≤ 1000
0 ≤ nums[i] ≤ 100
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)