Move All Zeroes to End of Array

Given an array of integers, write a code to move all zeroes to end of array. The order of all other elements of an array should be same.

Now, In this question we have to write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

NOTE : We have to solve this problem inplace without making a copy of the array.

For example –

Example 1:

Input : {1, 2, 0, 4, 0, 5, 3, 8}

Output: {1, 2, 4, 5, 3, 8, 0, 0}

In this example, All zeros are moved to the end of array and the relative order of non-zero elements is also maintained.

Example 2:

Input : {1, 0, 2, 3, 0, 0, 0, 2}

Output : {1, 2, 3, 2, 0, 0, 0, 0}

In this tutorial, I am going to discuss how we can push all zeroes to end of array using java code.

Before writing java code, let’s first discuss how we can move all 0’s in-place. Also, At the end of this post i have mentioned the link of a video tutorial.

Move Zeroes

Move Zeroes

Algorithm to Move Zeroes to End of Array

i) Traverse an array from left to right.

ii) While traversing an array maintain the count of non-zero elements in an array.

iii) For non-zero element, put the array element in arr[count] and increment the value of count.

iv) After complete traversal, non-zero element moved forward. Now, we can run a loop to put all zeros at the end of an array.

Programming video tutorials

Java program to reverse a string using stack

Move All Zeroes to End of Array – Java Code

We have already discussed the algorithm to move all the occurrences of 0’s to the end of array. Let’s write a function to push all the zeros that are present to the end of the array.

The time complexity of this approach is O(n) and it’s space complexity is O(1). We have not used any extra space.

Programming questions on arrays

Move Zeroes to End of Array LeetCode Solution

In this example, let’s write a java code to move all zeroes to end of array in-place (without using any extra space). Basically, we are going to write a code which shift all zeros to right of array.

Sort an array of 0s, 1s and 2s

Video Tutorial : Shift All Zeros to Right of Array

In this video tutorial, i have explained how to move zeroes to end of array without using extra space.

Move Zeros Video Tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.