Duplicate Zeros

Updated on 23 May, 2025
Duplicate Zeros header image

Problem Statement

The task is to modify an integer array named arr by duplicating each occurrence of the number zero. When a zero is duplicated, the elements that follow are shifted to the right. It is important to note that the modifications should adjust within the array's initial length, meaning any elements that would shift outside the array's bounds due to duplication should not be included. These changes should happen directly within the input array, hence altering it in-place without returning any new output. Additionally, take into account that only the zeros are duplicated, and each duplication should reflect immediately in the array.

Examples

Example 1

Input:

arr = [1,0,2,3,0,4,5,0]

Output:

[1,0,0,2,3,0,0,4]

Explanation:

After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2

Input:

arr = [1,2,3]

Output:

[1,2,3]

Explanation:

After calling your function, the input array is modified to: [1,2,3]

Constraints

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 9

Approach and Intuition

The nature of the problem requires us to analyze and possibly modify the array as we iterate through it. Given the need to double every zero encountered and shift subsequent items, direct array modification without additional storage consideration calls for a careful approach to ensure no data loss:

  1. Start by identifying the positions of zeroes that can be duplicated without exceeding the array limit. This involves reverse iterations or marking schemes.
  2. From the last element of the array, shift elements to the right whenever a zero is duplicated. This back-to-front method avoids overwriting elements that haven't been processed.
  3. Specifically treat cases with no zeros with a gentle bypass, ensuring minimal performance hit on such datasets.

This is a simplified intuition of how to address the problem respecting the original array’s constraints while ensuring maximum efficiency.

Solutions

  • Java
java
class Solution {
    public void expandZeros(int[] data) {
        int zeroCount = 0;
        int originalLength = data.length - 1;

        // Calculate number of zeros that can be duplicated
        for (int i = 0; i <= originalLength - zeroCount; i++) {
            if (data[i] == 0) {
                if (i == originalLength - zeroCount) {
                    data[originalLength] = 0;
                    originalLength -= 1;
                    break;
                }
                zeroCount++;
            }
        }

        // Duplicate zeros from the end to start in the array space
        int end = originalLength - zeroCount;
        for (int j = end; j >= 0; j--) {
            if (data[j] == 0) {
                data[j + zeroCount] = 0;
                zeroCount--;
                data[j + zeroCount] = 0;
            } else {
                data[j + zeroCount] = data[j];
            }
        }
    }
}

The given solution in Java focuses on solving the "Duplicate Zeros" problem. The implementation modifies the array data by duplicating zeros within the array itself, without using additional space for another array. This is how the solution works:

  1. Initialize a variable zeroCount to keep track of the number of zeros that can be duplicated without extending the array's size.

  2. Calculate the last valid index originalLength, which is data.length - 1.

  3. Traverse the array from the beginning to identify the positions of zeros and count how many of them can be duplicated without going out of bounds.

    • For each zero found, check if it's possible to duplicate it without exceeding the boundary of the array.
    • If a zero is found at a critical position (where duplicating it would exceed the array bounds), set the last element of the array to zero and adjust originalLength.
  4. Starting from the end of the array, copy and duplicate zeros towards the end:

    • Traverse the array backwards using the adjusted boundaries from earlier calculations (end = originalLength - zeroCount).
    • For each zero encountered, duplicate it by copying it to the appropriate positions determined by zeroCount.
    • For non-zero elements, directly copy them to the new position.

By following this approach, the method modifies the original array in-place to duplicate the zeroes while ensuring the resulting array doesn't exceed its original size. This is efficiently done using two main traversals of the array, making the time complexity primarily dependent on the size of the input array.

Comments

No comments yet.