This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
168. move zeros
One possible solution in JavaScript:
function moveZeros(arr) {
let i = 0;
for (let j = 0; j < arr.length; j++) {
if (arr[j] !== 0) {
arr[i] = arr[j];
i++;
}
}
for (let k = i; k < arr.length; k++) {
arr[k] = 0;
}
}
The idea of this solution is to use two pointers i
and j
to traverse the array. The pointer i
keeps track of the position where the next non-zero number should be placed, while j
scans the array for non-zero numbers. When a non-zero number is found at position j
, it is moved to position i
and i
is advanced. After the first loop, all non-zero numbers have been moved to the left side of the array, and the rest of the array is filled with zeros by a second loop from i
to the end. This approach has a time complexity of O(n) and a space complexity of O(1), since it only modifies the input array without using extra space.