-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1089-duplicate-zeros.js
More file actions
35 lines (32 loc) · 922 Bytes
/
1089-duplicate-zeros.js
File metadata and controls
35 lines (32 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 1089. Duplicate Zeros
* https://leetcode.com/problems/duplicate-zeros/
* Difficulty: Easy
*
* 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.
*/
/**
* @param {number[]} arr
* @return {void} Do not return anything, modify arr in-place instead.
*/
var duplicateZeros = function(arr) {
let zerosToAdd = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 0) zerosToAdd++;
}
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === 0) {
zerosToAdd--;
if (i + zerosToAdd + 1 < arr.length) {
arr[i + zerosToAdd + 1] = 0;
}
}
if (i + zerosToAdd < arr.length) {
arr[i + zerosToAdd] = arr[i];
}
}
};