Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem.
Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]‘ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.
public static void move(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
// index for non-zero
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
continue;
} else {
arr[index++] = arr[i];
}
}
for (int i = index; i < arr.length; i++) {
arr[i] = 0;
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 0, 4, 5, 6, 7, 0};
move(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}