Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
``bash
Input: nums = [0]
Output: [0]
Solution
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
* @time complexity: O(n)
* @space complexity: O(n)
*/
const moveZeroes = nums => {
// The first element should not be an non-zero
let nonZeroIndex = 0;
for (let i = 0; i < nums.length; i++) {
// Only replace the num when it is non-zero
if (nums[i] !== 0) {
nums[nonZeroIndex] = nums[i];
nonZeroIndex++;
}
}
// Rest of it should be zero
for (let i = nonZeroIndex; i < nums.length; i++) {
nums[i] = 0;
}
};
Another Solution
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
* @time complexity: O(n)
* @space complexity: O(n)
*/
const moveZeroes2 = function(nums) {
// The first element should not be an non-zero
let nonZeroIndex = 0;
for (let i = 0; i < nums.length; i++) {
// Swap the numbers only when the current number is non-zero
if (nums[i] !== 0) {
// Swap the numbers
const tmp= nums[nonZeroIndex];
nums[nonZeroIndex] = nums[i];
nums[i] = tmp;
nonZeroIndex++;
}
}
};
Test Case
const assert = require('chai').assert;
describe('Move Zeroes', () => {
describe('Solution 1', () => {
it('should move all zeroes to the end', () => {
const input = [0, 1, 0, 3, 12];
const expected = [1, 3, 12, 0, 0];
moveZeroes(input);
assert.deepEqual(input, expected);
});
it('should work with all zero array', () => {
const input = [0];
const expected = [0];
moveZeroes(input);
assert.deepEqual(input, expected);
});
});
describe('Solution 2', () => {
it('should move all zeroes to the end', () => {
const input = [0, 1, 0, 3, 12];
const expected = [1, 3, 12, 0, 0];
moveZeroes2(input);
assert.deepEqual(input, expected);
});
it('should work with all zero array', () => {
const input = [0];
const expected = [0];
moveZeroes2(input);
assert.deepEqual(input, expected);
});
});
});
Move Zeroes
Solution 1
✓ should move all zeroes to the end
✓ should work with all zero array
Solution 2
✓ should move all zeroes to the end
✓ should work with all zero array
4 passing (18ms)