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).
Example:
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
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 run a loop that makes all elements zero from ‘count’ till end of the array.
Below is the implementation of the above approach.
C
#include <stdio.h>
void pushZerosToEnd( int arr[], int n)
{
int count = {0};
for ( int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < n)
arr[count++] = 0;
}
int main()
{
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
int n = sizeof (arr) / sizeof (arr[0]);
pushZerosToEnd(arr, n);
printf ( "%s\n" , "Array after pushing all zeros to end of array:" );
for ( int i = 0; i < n; i++)
printf ( "%d " , arr[i]);
return 0;
}
|
C++
#include <algorithm>
#include <iostream>
#include <vector>
void push_zeros_to_end(std::vector< int >& arr)
{
std::stable_partition(arr.begin(),
arr.end(),
[]( int n) { return n != 0; });
}
int main()
{
std::vector< int > arr{1,9,8,4,0,0,2,7,0,6,0,9};
push_zeros_to_end(arr);
for ( const auto & i : arr)
std::cout << i << ' ' ;
std::cout << "\n" ;
return 0;
}
|
Java
import java.io.*;
class PushZero
{
static void pushZerosToEnd( int arr[], int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
if (arr[i] != 0 )
arr[count++] = arr[i];
while (count < n)
arr[count++] = 0 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 9 , 8 , 4 , 0 , 0 , 2 , 7 , 0 , 6 , 0 , 9 };
int n = arr.length;
pushZerosToEnd(arr, n);
System.out.println( "Array after pushing zeros to the back: " );
for ( int i= 0 ; i<n; i++)
System.out.print(arr[i]+ " " );
}
}
|
Python3
def pushZerosToEnd(arr, n):
count = 0
for i in range (n):
if arr[i] ! = 0 :
arr[count] = arr[i]
count + = 1
while count < n:
arr[count] = 0
count + = 1
arr = [ 1 , 9 , 8 , 4 , 0 , 0 , 2 , 7 , 0 , 6 , 0 , 9 ]
n = len (arr)
pushZerosToEnd(arr, n)
print ( "Array after pushing all zeros to end of array:" )
print (arr)
|
C#
using System;
class PushZero
{
static void pushZerosToEnd( int []arr, int n)
{
int count = 0;
for ( int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < n)
arr[count++] = 0;
}
public static void Main ()
{
int []arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
int n = arr.Length;
pushZerosToEnd(arr, n);
Console.WriteLine( "Array after pushing all zeros to the back: " );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
PHP
<?php
function pushZerosToEnd(& $arr , $n )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
if ( $arr [ $i ] != 0)
$arr [ $count ++] = $arr [ $i ];
while ( $count < $n )
$arr [ $count ++] = 0;
}
$arr = array (1, 9, 8, 4, 0, 0,
2, 7, 0, 6, 0, 9);
$n = sizeof( $arr );
pushZerosToEnd( $arr , $n );
echo "Array after pushing all " .
"zeros to end of array :\n" ;
for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ] . " " ;
?>
|
Javascript
<script>
function pushZerosToEnd(arr, n)
{
let count = 0;
for (let i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < n)
arr[count++] = 0;
}
let arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9];
let n = arr.length;
pushZerosToEnd(arr, n);
document.write( "Array after pushing all zeros to end of array :<br>" );
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
OutputArray after pushing all zeros to end of array:
1 9 8 4 2 7 6 9 0 0 0 0
Time Complexity: O(n) where n is the size of elements of the input array.
Auxiliary Space: O(1)
Method 2: Partitioning the array
Approach: The approach is pretty simple. We will use 0 as a pivot element and whenever we see a non zero element we will swap it with the pivot element. So all the non zero element will come at the beginning.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = sizeof (A) / sizeof (A[0]);
int j = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
swap(A[j], A[i]);
j++;
}
}
for ( int i = 0; i < n; i++) {
cout << A[i] << " " ;
}
return 0;
}
|
C
#include <stdio.h>
int main()
{
int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = sizeof (A) / sizeof (A[0]);
int j = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
j++;
}
}
for ( int i = 0; i < n; i++) {
printf ( "%d " , A[i]);
}
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int [] A = { 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 };
int n = A.length;
int j = 0 ;
for ( int i = 0 ; i < n; i++) {
if (A[i] != 0 ) {
swap(A, j, i);
j++;
}
}
for ( int i = 0 ; i < n; i++) {
System.out.print(A[i] + " " );
}
}
public static void swap( int [] A, int a, int b)
{
int temp = A[a];
A[a] = A[b];
A[b] = temp;
}
}
|
Python3
A = [ 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 ]
n = len (A)
j = 0
for i in range (n):
if A[i] ! = 0 :
A[j], A[i] = A[i], A[j]
j + = 1
print (A)
|
C#
using System;
public static class GFG
{
public static void Main()
{
int [] A = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = A.Length;
int j = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
int temp = A[j];
A[j] = A[i];
A[i] = temp;
j++;
}
}
for ( int i = 0; i < n; i++) {
Console.Write(A[i]);
Console.Write( " " );
}
}
}
|
Javascript
<script>
let A = [5, 6, 0, 4, 6, 0, 9, 0, 8];
let n = A.length;
let j = 0;
for (let i = 0; i < n; i++) {
if (A[i] != 0) {
swap(A, j, i);
j++;
}
}
for (let i = 0; i < n; i++) {
document.write(A[i] + " " );
}
function swap(A, a, b) {
let temp = A[a];
A[a] = A[b];
A[b] = temp;
}
</script>
|
Time Complexity: O(N), where N is the size of elements of the input array.
Auxiliary Space: O(1)
Method 3: using C++ STL
In this approach, we will traverse the whole array and will count the number of zeros present in the array. While counting we will delete the zero from the array.
After completing the above process, we will push back the count number of zeros into the array.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void move_zeros_to_right(vector< int >& m)
{
int count = 0;
int length=m.size();
for ( int i = 0; i < length; i++) {
if (m[i] == 0) {
count++;
m.erase(m.begin() + i);
i--;
length--;
}
}
for ( int i = 0; i < count; i++) {
m.push_back(0);
}
cout << "array after shifting zeros to right side: "
<< endl;
for ( int i = 0; i < m.size(); i++) {
cout << m[i] << " " ;
}
}
int main()
{
vector< int > m{ 5, 6, 0, 4, 6, 0, 9, 0, 8 };
move_zeros_to_right(m);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void move_zeros_to_right(ArrayList<Integer> m)
{
int count = 0 ;
for ( int i = 0 ; i < m.size(); i++) {
if (m.get(i) == 0 ) {
count++;
m.remove(i);
i--;
}
}
for ( int i = 0 ; i < count; i++)
{
m.add( 0 );
}
System.out.println( "array after shifting zeros to right side: " );
for ( int i = 0 ; i < m.size(); i++)
{
System.out.print(m.get(i) + " " );
}
}
public static void main(String[] args)
{
ArrayList<Integer> m = new ArrayList<>(Arrays.asList( 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 ));
move_zeros_to_right(m);
}
}
|
Python3
arr = [ 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 ]
nonZeroValues = [x for x in arr if x ! = 0 ]
zeroes = [j for j in arr if j = = 0 ]
arr = nonZeroValues + zeroes
print ( "array after shifting zeros to right side: " , arr)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
class GFG
{
static void move_zeros_to_right(List< int > m)
{
var count = 0;
for ( int i = 0; i < m.Count; i++)
{
if (m[i] == 0)
{
count++;
m.RemoveAt(i);
i--;
}
}
for ( int i = 0; i < count; i++)
{
m.Add(0);
}
Console.WriteLine( "array after shifting zeros to right side: " );
for ( int i = 0; i < m.Count; i++)
{
Console.Write( string .Join( ", " ,m[i]) + " " );
}
}
public static void Main()
{
List< int > m = new List< int >( new int [] {5,6,0,4,6,0,9,0,8});
GFG.move_zeros_to_right(m);
}
}
|
Javascript
function move_zeros_to_right( m)
{
let count = 0;
for (let i = 0; i < m.length; i++) {
if (m[i] == 0) {
count++;
m.splice(i,1);
i--;
}
}
for (let i = 0; i < count; i++)
{
m.push(0);
}
console.log( "array after shifting zeros to right side: " );
var str= m.join( ' ' );
console.log(str)
}
let m = [ 5, 6, 0, 4, 6, 0, 9, 0, 8 ];
move_zeros_to_right(m);
|
Outputarray after shifting zeros to right side:
5 6 4 6 9 8 0 0 0
Time complexity: O(N), where N is the size of elements of the input array.
Auxiliary space: O(1).
Method-4: using extra space
In this approach, we will take an array of the same size as the input array and run a for loop on the input array. In that for loop, if the element does not equal 0, then place that element in the new array and if that element is 0 increase the count of 0. Then add as many 0 In that new array as we have the count of zeroes. Then copy elements of this new array into our old/input array.
Below is the implementation of the above approach
C
#include <stdio.h>
void move_zeros_to_right( int A[], int n)
{
int B[n];
int j = 0;
int count = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
B[j] = A[i];
j++;
}
else {
count++;
}
}
while (count > 0) {
B[j] = 0;
count--;
j++;
}
for ( int i = 0; i < n; i++) {
A[i] = B[i];
}
printf ( "array after shifting zeros to right side:\n" );
for ( int i = 0; i < n; i++) {
printf ( "%d " , A[i]);
}
}
int main()
{
int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = sizeof (A) / sizeof (A[0]);
move_zeros_to_right(A, n);
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = sizeof (A) / sizeof (A[0]);
int B[n];
int j = 0;
int count = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
B[j] = A[i];
j++;
}
else {
count++;
}
}
while (count > 0) {
B[j] = 0;
count--;
j++;
}
for ( int i = 0; i < n; i++) {
A[i] = B[i];
}
for ( int i = 0; i < n; i++) {
cout << A[i] << " " ;
}
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int [] A = { 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 };
int n = A.length;
int [] B = new int [n];
int j = 0 ;
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (A[i] != 0 ) {
B[j] = A[i];
j++;
}
else {
count++;
}
}
while (count > 0 ) {
B[j] = 0 ;
count--;
j++;
}
for ( int i = 0 ; i < n; i++) {
A[i] = B[i];
}
for ( int i = 0 ; i < n; i++) {
System.out.print(A[i] + " " );
}
}
}
|
Python3
A = [ 5 , 6 , 0 , 4 , 6 , 0 , 9 , 0 , 8 ]
n = len (A)
B = [ 0 ] * n
j = 0
count = 0
for i in range (n):
if A[i] ! = 0 :
B[j] = A[i]
j + = 1
else :
count + = 1
while count > 0 :
B[j] = 0
count - = 1
j + = 1
for i in range (n):
A[i] = B[i]
for i in range (n):
print (A[i], end = ' ' )
|
C#
using System;
class MainClass {
public static void Main( string [] args)
{
int [] A = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = A.Length;
int [] B = new int [n];
int j = 0;
int count = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != 0) {
B[j] = A[i];
j++;
}
else {
count++;
}
}
while (count > 0) {
B[j] = 0;
count--;
j++;
}
for ( int i = 0; i < n; i++) {
A[i] = B[i];
}
for ( int i = 0; i < n; i++) {
Console.Write(A[i] + " " );
}
}
}
|
Javascript
let A = [5, 6, 0, 4, 6, 0, 9, 0, 8];
let n = A.length;
let B = new Array(n);
let j = 0;
let count = 0;
for (let i = 0; i < n; i++) {
if (A[i] !== 0) {
B[j] = A[i];
j++;
}
else {
count++;
}
}
while (count > 0) {
B[j] = 0;
count--;
j++;
}
for (let i = 0; i < n; i++) {
A[i] = B[i];
}
for (let i = 0; i < n; i++) {
console.log(A[i] + " " );
}
|
Output:
5 6 4 6 9 8 0 0 0
Time complexity: O(N), where N is the size of elements of the input array.
Space complexity: O(N), for array B
This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.