Zeros to the End (Medium)
Good afternoon! Here's our prompt for today.
You may see this problem at Oracle, Groupon, Quora, Spotify, Morgan Stanley, Glassdoor, and Cockroach Labs.
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
-1000000000and1000000000 - Expected time complexity :
O(n) - Expected space complexity :
O(1)
xxxxxxxxxx48
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]`'OUTPUT
Results will appear here.