Move zeros to the end - Coding Problem

Write a method to move all zero elements of an array to the end and make sure the order of non-zero elements is intact.

Solution

To achieve the solution, we must separate the zeros from non-zero elements while keeping track of the order of non-zero elements and the count of zeros.

We can simply do so by using the same array we have. We need to move the non-zero elements to the left and fill out the remaining length of array with zeros, thus making sure order is maintained along with size of array.

Implementation

Javascript
Python
function moveZerosToEnd(numbers) {
	let index = 0;
	for (let i = 0; i < numbers.length; i++) {
		if (numbers[i] != 0) {
			numbers[index++] = numbers[i];
		}
	}

	for (let j = index; j < numbers.length; j++) {
		numbers[j] = 0;
	}

	return numbers;
}

//Input: moveZerosToEnd([ 11, 56, 0, 0, 32, 0, 9, 0 ]));
//Output: [11, 56, 32, 9, 0, 0, 0, 0]
def moveZerosToEnd(numbers):
	index = 0
	for n in range(len(numbers)):
		if numbers[n] != 0:
			numbers[index] = numbers[n]
			index += 1

	for j in range(index, len(numbers)):
		numbers[j] = 0

	return numbers

#Input: print(moveZerosToEnd([22, 90, 0, 0, 76, 0, 11]))
#Output: [22, 90, 76, 11, 0, 0, 0]
// third
fourth