Problem Description
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. Modify the array in place without using extra space for another array.
Key Insights
- The array must be modified in place.
- Duplicating a zero shifts the rest of the elements; hence, working backwards avoids overwriting unprocessed values.
- A two pointer approach is optimal: one pointer for iterating the original array and another to build the result from the end.
- Handle edge cases where duplicating a zero might exceed the bounds of the array.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1) in terms of additional storage.
Solution
The approach begins by calculating the number of zeros that would need to be duplicated if space were unlimited. However, since the array has fixed length, we use these counts to determine the final positions for each element by working backwards. Two pointers are used: one at the end of the original array (considering the potential extra zeros) and one at the actual end of the array. As we iterate backwards, if the element is zero, we write it twice (subject to boundary conditions); otherwise, we simply copy the element. This prevents overwriting data that hasn’t been processed yet.