Duplicate Zeros LeetCode solution in JavaScript

1
/**
2
* @param {number[]} arr
3
* @return {void} Do not return anything, modify arr in-place instead.
4
*/
5
var duplicateZeros = function (arr) {
6
// Variables
7
const originalLength = arr.length;
8

9
// Iterate over all the numbers in 'arr', if the number is 0 we duplicate it and skip the next loop iteration to prevent an overflow.
10
for (let idx = 0; idx < arr.length; idx++) {
11
const number = arr[idx];
12
if (number === 0) {
13
arr.splice(idx, 0, 0);
14
idx += 1;
15
}
16
}
17

18
// Here we restore the array to its original length.
19
return (arr.length = originalLength);
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0