TheLeanProgrammer
Published in

TheLeanProgrammer

JavaScript | Move Zeroes

Interview Question

This question comes under a broad category of “Array Transformation”.

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:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Solution:

The 2 requirements of the question are:

  1. Move all the 0’s to the end of array.
  2. All the non-zero elements must retain their original order.

Let's look into two implementation -

In the first implementation,

  • the first loop deletes the zeros using splice().
  • the second loop pushes the zeros to the end of arrays using push().
var moveZeroes = function(nums) {
let zeros = 0
for (let i = 0; i < nums.length; i++) {
let isZero = nums[i] === 0
if (isZero){
zeros++
nums.splice(i, 1)
i--
}
}
for (let i = 0; i < zeros; i++){
nums.push(0)
}
return nums
};

Second Implementation,

  • using one for loop, we will delete the zeros using splice() and push the zeros to the end of the array using push().
var moveZeroes = function(nums) {
for (let i = nums.length - 1; i >= 0; i--) {
nums[i] === 0 && nums.splice(i, 1) && nums.push(0);
}
return nums
};

Summary

  • use splice() method of the array, to delete the zeros and add those zeros to the end of the array using push().

This problem is very popular in coding interviews.

Keep learning, keep growing!

Don’t forget to follow me for more such articles, and subscribe to our newsletter.

Let’s connect on LinkedIn!. Please read more for more data structure javascript question.

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sonika | Working at Walmart | startlearncoding.com

Sonika | Working at Walmart | startlearncoding.com

Working in Walmart as Senior UI Developer | React | JavaScript | Data Structure