Skip to main content

< Back to Data Structures and Algorithms

LeetCode 1089 · Arrays

Duplicate Zeros

Doubles every zero in place, shifting the rest right and dropping whatever falls off the end.

Step through it

Examples
Edge cases
arr
  1. 10
  2. 01
  3. 22
  4. 33
  5. 04
  6. 45
  7. 56
  8. 07

Step 0 of 36

Output

Running… play or step to the end.

The code

/**
 * Duplicates 0s in a fixed size array.
 * When a 0 is duplicated, shift all next entries to the right.
 * Maintain the original length of the array.
 * @param {number[]} arr
 * @return {void} Do not return anything, modify arr in-place instead.
 */
 const duplicateZeros = arr => {
    // O(n) loop over every item within the array.
    for (let i=0; i < arr.length; i++) {
        // Value is 0.
        if (arr[i] === 0) {
            // Add a new 0 to the right of current 0.
            arr.splice(i, 0, 0)
            // Remove last item from the array.
            arr.pop()
            // Increase iteration so it skips the new next 0.
            i = i + 1
        }
    }
};

View it on GitHub (opens in a new tab)