LeetCode Problem - Link



Problem

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. Do the above modifications to the input array in place and do not return anything.

 

Example:

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]


Sequential Approach

/**
 * @param {number[]} arr
 * @return {void} Do not return anything, modify arr in-place instead.
 */
var duplicateZeros = function (arr) {
    var index = arr.length;

    while (index > -1) {
        if (arr[index] == 0) {
            shiftArrElements(arr, index)
        }
        index -= 1
    }
};


var shiftArrElements = (arr, shiftFromIndex) => {
    // A utility function that shifts all the elements by one to right,
    // while getting rid of the items that overflow array's length
    for (var i = arr.length - 1; i > shiftFromIndex; i--) {
        arr[i] = arr[i - 1]
    }
    arr[shiftFromIndex] = 0
}