Given an integer array, move all zeros present in it to the end. The solution should maintain the relative order of items in the array and should not use constant space.

For example,

Input:  { 6, 0, 8, 2, 3, 0, 4, 0, 1 }
 
Output: { 6, 8, 2, 3, 4, 1, 0, 0, 0 }

Practice this problem

The idea is simple – if the current element is non-zero, place the element at the next available position in the array. After all elements in the array are processed, fill all remaining indices by 0. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

6 8 2 3 4 1 0 0 0

Java


Download  Run Code

Output:

[6, 8, 2, 3, 4, 1, 0, 0, 0]

Python


Download  Run Code

Output:

[6, 8, 2, 3, 4, 1, 0, 0, 0]

The time complexity of the above solution is O(n), where n is the size of the input.

Using partitioning logic of Quicksort

We can also solve this problem in one scan of the array by modifying Quicksort’s partitioning logic. The idea is to use 0 as a pivot element and make one pass of the partition process. The partitioning logic reads all elements and swap every non-pivot element with the first occurrence of the pivot.

Following is the implementation in C, Java, and Python based on the above idea:

C


Download  Run Code

Output:

6 8 2 3 4 1 0 0 0

Java


Download  Run Code

Output:

[6, 8, 2, 3, 4, 1, 0, 0, 0]

Python


Download  Run Code

Output:

[6, 8, 2, 3, 4, 1, 0, 0, 0]

The time complexity of the above solution is O(n), where n is the size of the input.

 
Exercise: Modify the solution so that all 1's would come first.