Good morning! Here's our prompt for today.
Write a method that moves all zeros in an array to its end. You should maintain the order of all other elements. Here's an example:
JAVASCRIPT
1zerosToEnd([1, 0, 2, 0, 4, 0])
2// [1, 2, 4, 0, 0, 0]

Here's another one:
JAVASCRIPT
1zerosToEnd([1, 0, 2, 0, 4, 0])
2// [1, 2, 4, 0, 0, 0]
Fill in the following function signature:
JAVASCRIPT
1function zerosToEnd(nums) {
2 return;
3};
Can you do this without instantiating a new array?
Constraints
- Length of the array <=
100000
- The array will always contain integer values between
-1000000000
and1000000000
- Expected time complexity :
O(n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
48
var assert = require('assert');
​
function zerosToEnd(nums) {
// Fill in this method
return nums;
}
​
console.log(zerosToEnd([1, 0, 2, 0, 4, 0]));
​
try {
assert.deepEqual(zerosToEnd([1, 0, 2, 0, 4, 0]), [1, 2, 4, 0, 0, 0]);
​
console.log(
'PASSED: `zerosToEnd([1, 0, 2, 0, 4, 0])` should get us `[1, 2, 4, 0, 0, 0]`'
);
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(
zerosToEnd([4, 13, 0, 2, 0, 0, 15, 0]),
[4, 13, 2, 15, 0, 0, 0, 0]
);
​
console.log(
'PASSED: `zerosToEnd([4, 13, 0, 2, 0, 0, 15, 0])` should get us `[4, 13, 2, 15, 0, 0, 0, 0]`'
);
} catch (err) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

We'll now take you through what you need to know.
How do I use this guide?