0

Using the solution below, I am able to get the solution correctly logged, however, it seems that Leetcode gets a different solution than my answer.

/**
  * @param {number[]} arr
  * @return {void} Do not return anything, modify arr in-place instead.
  */
var duplicateZeros = function(arr) {
  let finalLength = arr.length;
  for (let i = 0; i < finalLength; i++) {
    if(arr[i] == 0) {
        arr.splice(i, 0, 0);
        i++;
    }
  }
  arr = arr.slice(0, finalLength);
  console.log(arr);
};

enter image description here

Mister Jojo
  • 16,804
  • 3
  • 16
  • 39
  • [`slice`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/slice) creates a copy of the array and doesn’t mutate it. Assigning to `arr` doesn’t do much; it gets you the correct result in the `console.log`, but you’re not changing the “reference” of `arr` outside of the function. Instead, use a mutating action such as `splice` at the end: `arr.splice(0, finalLength);` or something. – Sebastian Simon Mar 25 '22 at 15:27

0 Answers0