Duplicate Zeros - Problem

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note: Elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Input & Output

Example 1 — Basic Duplication
$ Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
💡 Note: Each zero is duplicated, shifting remaining elements right. Elements 5,0 are dropped as they exceed array length.
Example 2 — No Zeros
$ Input: arr = [1,2,3]
Output: [1,2,3]
💡 Note: No zeros to duplicate, array remains unchanged.
Example 3 — All Zeros
$ Input: arr = [0,0,0]
Output: [0,0,0]
💡 Note: First zero is duplicated, second zero pushes remaining elements out of bounds.

Constraints

  • 1 ≤ arr.length ≤ 104
  • 0 ≤ arr[i] ≤ 9

Visualization

Tap to expand
Duplicate Zeros - Optimal Solution INPUT Original Array (length = 8) 1 0 2 3 0 4 5 0 0 1 2 3 4 5 6 7 = Zero (to duplicate) Constraints: - Fixed length array - Modify in-place - Shift right on duplicate - Elements beyond length are discarded Zeros found: 3 ALGORITHM STEPS 1 Count Zeros Count zeros to find new length: 8 + 3 = 11 2 Two Pointers Setup i = 7 (end of array) j = 10 (virtual end) 3 Traverse Backwards If j is in bounds: arr[j] = arr[i] If arr[i]=0, duplicate it 4 Handle Edge Case If zero at boundary, only write once Time: O(n) | Space: O(1) Two-pass approach FINAL RESULT Modified Array 1 0 0 2 3 0 0 4 0 1 2 3 4 5 6 7 = Duplicated zero Transformation: [1,0,2,3,0,4,5,0] [1,0,0,2,3,0,0,4] Discarded Elements: 5, 0 (beyond len) OK Key Insight: Process array from RIGHT to LEFT to avoid overwriting elements we haven't processed yet. First count zeros to determine the "virtual" extended length, then work backwards writing values only when the write position is within bounds. This achieves O(1) space complexity. TutorialsPoint - Duplicate Zeros | Optimal Two-Pointer Approach
Asked in
Apple 15 Microsoft 12
32.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen