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 run a loop that makes all elements zero from ‘count’ till end of the array.
Below is the implementation of the above approach.
C
// A C program to move all zeroes at the end of array
#include <stdio.h>
// Function which pushes all zeros to end of an array.
voidpushZerosToEnd(intarr[], intn)
{
intcount = {0}; // Count of non-zero elements
// Traverse the array. If element encountered is non-
// zero, then replace the element at index 'count'
// with this element
for(inti = 0; i < n; i++)
if(arr[i] != 0)
arr[count++] = arr[i]; // here count is
// incremented
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while(count < n)
arr[count++] = 0;
}
// Driver program to test above function
intmain()
{
intarr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
intn = sizeof(arr) / sizeof(arr[0]);
pushZerosToEnd(arr, n);
printf("%s\n", "Array after pushing all zeros to end of array:");
for(inti = 0; i < n; i++)
printf("%d ", arr[i]);
return0;
}
C++
#include <algorithm>
#include <iostream>
#include <vector>
voidpush_zeros_to_end(std::vector<int>& arr)
{
std::stable_partition(arr.begin(),
arr.end(),
[](intn) { returnn != 0; });
}
intmain()
{
std::vector<int> arr{1,9,8,4,0,0,2,7,0,6,0,9};
push_zeros_to_end(arr);
for(constauto& i : arr)
std::cout << i << ' ';
std::cout << "\n";
return0;
}
Java
/* Java program to push zeroes to back of array */
importjava.io.*;
classPushZero
{
// Function which pushes all zeros to end of an array.
staticvoidpushZerosToEnd(intarr[], intn)
{
intcount = 0; // Count of non-zero elements
// Traverse the array. If element encountered is
// non-zero, then replace the element at index 'count'
// with this element
for(inti = 0; i < n; i++)
if(arr[i] != 0)
arr[count++] = arr[i]; // here count is
// incremented
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while(count < n)
arr[count++] = 0;
}
/*Driver function to check for above functions*/
publicstaticvoidmain (String[] args)
{
intarr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
intn = arr.length;
pushZerosToEnd(arr, n);
System.out.println("Array after pushing zeros to the back: ");
for(inti=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}
/* This code is contributed by Devesh Agrawal */
Python3
# Python3 code to move all zeroes
# at the end of array
# Function which pushes all
# zeros to end of an array.
defpushZerosToEnd(arr, n):
count =0# Count of non-zero elements
# Traverse the array. If element
# encountered is non-zero, then
# replace the element at index
# 'count' with this element
fori inrange(n):
ifarr[i] !=0:
# here count is incremented
arr[count] =arr[i]
count+=1
# Now all non-zero elements have been
# shifted to front and 'count' is set
# as index of first 0. Make all
# elements 0 from count to end.
whilecount < n:
arr[count] =0
count +=1
# Driver code
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)
# This code is contributed by "Abhishek Sharma 44"
C#
/* C# program to push zeroes to back of array */
usingSystem;
classPushZero
{
// Function which pushes all zeros
// to end of an array.
staticvoidpushZerosToEnd(int[]arr, intn)
{
// Count of non-zero elements
intcount = 0;
// Traverse the array. If element encountered is
// non-zero, then replace the element
// at index â..countâ.. with this element
for(inti = 0; i < n; i++)
if(arr[i] != 0)
// here count is incremented
arr[count++] = arr[i];
// Now all non-zero elements have been shifted to
// front and â..countâ.. is set as index of first 0.
// Make all elements 0 from count to end.
while(count < n)
arr[count++] = 0;
}
// Driver function
publicstaticvoidMain ()
{
int[]arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
intn = arr.Length;
pushZerosToEnd(arr, n);
Console.WriteLine("Array after pushing all zeros to the back: ");
for(inti = 0; i < n; i++)
Console.Write(arr[i] +" ");
}
}
/* This code is contributed by Anant Agrawal */
PHP
<?php
// A PHP program to move all
// zeroes at the end of array
// Function which pushes all
// zeros to end of an array.
functionpushZerosToEnd(&$arr, $n)
{
// Count of non-zero elements
$count= 0;
// Traverse the array. If
// element encountered is
// non-zero, then replace
// the element at index
// 'count' with this element
for($i= 0; $i< $n; $i++)
if($arr[$i] != 0)
// here count is incremented
$arr[$count++] = $arr[$i];
// Now all non-zero elements
// have been shifted to front
// and 'count' is set as index
// of first 0. Make all elements
// 0 from count to end.
while($count< $n)
$arr[$count++] = 0;
}
// Driver Code
$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] . " ";
// This code is contributed
// by ChitraNayal
?>
Javascript
<script>
// A JavaScript program to move all zeroes at the end of array
// Function which pushes all zeros to end of an array.
functionpushZerosToEnd(arr, n)
{
let count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is non-
// zero, then replace the element at index 'count'
// with this element
for(let i = 0; i < n; i++)
if(arr[i] != 0)
arr[count++] = arr[i]; // here count is
// incremented
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while(count < n)
arr[count++] = 0;
}
// Driver code
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] + " ");
// This code is contributed by Surbhi Tyagi.
</script>
Output
Array 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++
// C++ Program to move all zeros to the end
#include <bits/stdc++.h>
usingnamespacestd;
intmain()
{
intA[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
intn = sizeof(A) / sizeof(A[0]);
intj = 0;
for(inti = 0; i < n; i++) {
if(A[i] != 0) {
swap(A[j], A[i]); // Partitioning the array
j++;
}
}
for(inti = 0; i < n; i++) {
cout << A[i] << " "; // Print the array
}
return0;
}
C
// C Program to move all zeros to the end
#include <stdio.h>
intmain()
{
intA[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
intn = sizeof(A) / sizeof(A[0]);
intj = 0;
for(inti = 0; i < n; i++) {
if(A[i] != 0) {
inttemp = A[i]; // Partitioning the array
A[i] = A[j];
A[j] = temp;
j++;
}
}
for(inti = 0; i < n; i++) {
printf("%d ", A[i]); // Print the array
}
return0;
}
Java
// Java Program to move all zeros to the end
importjava.util.*;
publicclassMain {
publicstaticvoidmain(String[] args)
{
int[] A = { 5, 6, 0, 4, 6, 0, 9, 0, 8};
intn = A.length;
intj = 0;
for(inti = 0; i < n; i++) {
if(A[i] != 0) {
// Swap - A[j] , A[i]
swap(A, j, i); // Partitioning the array
j++;
}
}
for(inti = 0; i < n; i++) {
System.out.print(A[i] + " "); // Print the array
}
}
// Utility function to swap two elements of an array
publicstaticvoidswap(int[] A, inta, intb)
{
inttemp = A[a];
A[a] = A[b];
A[b] = temp;
}
}
// This code is contributed by tapeshdua420.
Python3
# Python Program to move all zeros to the end
A =[5, 6, 0, 4, 6, 0, 9, 0, 8]
n =len(A)
j =0
fori inrange(n):
ifA[i] !=0:
A[j], A[i] =A[i], A[j] # Partitioning the array
j +=1
print(A) # Print the array
# This code is contributed by Tapesh(tapeshdua420)
C#
usingSystem;
publicstaticclassGFG
{
// C# Program to move all zeros to the end
publicstaticvoidMain()
{
int[] A = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
intn = A.Length;
intj = 0;
for(inti = 0; i < n; i++) {
if(A[i] != 0) {
inttemp = A[j];
A[j] = A[i];
A[i] = temp;
j++;
}
}
for(inti = 0; i < n; i++) {
Console.Write(A[i]);
Console.Write(" ");
}
}
}
// This code is contributed by Aarti_Rathi
Javascript
<script>
// Javascript Program to move all zeros to the end
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] , A[i]
swap(A, j, i); // Partitioning the array
j++;
}
}
for(let i = 0; i < n; i++) {
document.write(A[i] + " "); // Print the array
}
// Utility function to swap two elements of an array
functionswap(A, a, b) {
let temp = A[a];
A[a] = A[b];
A[b] = temp;
}
// This code is contributed by Saurabh Jaiswal
</script>
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. 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++
// C++ program to shift all zeros
// to right most side of array
// without affecting order of non-zero
// elements.
#include <bits/stdc++.h>
usingnamespacestd;
// function to shift zeros
voidmove_zeros_to_right(vector<int>& m)
{
intcount = 0;
intlength=m.size();
for(inti = 0; i < length; i++) {
if(m[i] == 0) {
count++;
// deleting the element from vector
m.erase(m.begin() + i);
i--;
// The length gets decresed after erasing each element
length--;
}
}
for(inti = 0; i < count; i++) {
// inserting the zero into vector
m.push_back(0);
}
cout << "array after shifting zeros to right side: "
<< endl;
for(inti = 0; i < m.size(); i++) {
// printing desired vector
cout << m[i] << " ";
}
}
// driver code
intmain()
{
vector<int> m{ 5, 6, 0, 4, 6, 0, 9, 0, 8 };
// function call
move_zeros_to_right(m);
return0;
}
Java
// Java program to shift all zeros
// to right most side of array
// without affecting order of non-zero
// elements.
importjava.util.*;
classGFG
{
// function to shift zeros
staticvoidmove_zeros_to_right(ArrayList<Integer> m)
{
intcount = 0;
for(inti = 0; i < m.size(); i++) {
if(m.get(i) == 0) {
count++;
// deleting the element from vector
m.remove(i);
i--;
}
}
for(inti = 0; i < count; i++)
{
// inserting the zero into arraylist
m.add(0);
}
System.out.println("array after shifting zeros to right side: ");
print( "array after shifting zeros to right side: ", arr)
C#
// Include namespace system
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Collections;
classGFG
{
// function to shift zeros
staticvoidmove_zeros_to_right(List<int> m)
{
varcount = 0;
for(inti = 0; i < m.Count; i++)
{
if(m[i] == 0)
{
count++;
// deleting the element from vector
m.RemoveAt(i);
i--;
}
}
for(inti = 0; i < count; i++)
{
// inserting the zero into arraylist
m.Add(0);
}
Console.WriteLine("array after shifting zeros to right side: ");
for(inti = 0; i < m.Count; i++)
{
// printing desired arraylist
Console.Write(string.Join(", ",m[i]) + " ");
}
}
// Driver Code
publicstaticvoidMain()
{
List<int> m = newList<int>(newint[] {5,6,0,4,6,0,9,0,8});
// function call
GFG.move_zeros_to_right(m);
}
}
// This code is contributed by aadityaburujwale.
Javascript
// Javascript program to shift all zeros
// to right most side of array
// without affecting order of non-zero
// elements.
// function to shift zeros
functionmove_zeros_to_right( m)
{
let count = 0;
for(let i = 0; i < m.length; i++) {
if(m[i] == 0) {
count++;
// deleting the element from vector
//m.erase(m.begin() + i);
m.splice(i,1);
i--;
}
}
for(let i = 0; i < count; i++)
{
// inserting the zero into vector
m.push(0);
}
console.log( "array after shifting zeros to right side: ");
varstr= m.join(' ');
console.log(str)
}
// driver code
let m = [ 5, 6, 0, 4, 6, 0, 9, 0, 8 ];
// function call
move_zeros_to_right(m);
// This code is contributed by garg28harsh.
Output
array 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++
// C++ Program to move all zeros to the end
#include <bits/stdc++.h>
usingnamespacestd;
intmain()
{
intA[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
intn = sizeof(A) / sizeof(A[0]);
intB[n];
intj=0;
intcount=0;
for(inti=0;i<n;i++){
if(A[i]!=0){
B[j]=A[i];
j++;
}
else{
count++;
}
}
while(count>0){
B[j]=0;
count--;
j++;
}
for(inti = 0; i < n; i++) {
A[i]=B[i];
}
for(inti = 0; i < n; i++) {
cout << A[i] << " "; // Print the array
}
return0;
}
Java
// Java program to move all zeros to the end
importjava.util.*;
publicclassMain {
publicstaticvoidmain(String[] args)
{
int[] A = { 5, 6, 0, 4, 6, 0, 9, 0, 8};
intn = A.length;
int[] B = newint[n];
intj = 0;
intcount = 0;
for(inti = 0; i < n; i++) {
if(A[i] != 0) {
B[j] = A[i];
j++;
}
else{
count++;
}
}
while(count > 0) {
B[j] = 0;
count--;
j++;
}
for(inti = 0; i < n; i++) {
A[i] = B[i];
}
for(inti = 0; i < n; i++) {
System.out.print(A[i] + " "); // Print the array
}
}
}
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 byChandra Prakash. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Please Login to comment...