Move all zeroes to end of array - GeeksforGeeks

14 Dec, 2021
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 that run a loop which makes all elements zero from ‘count’ till end of the array.Below is the implementation of the above approach.  
C
C++
Java
Python3
C#
PHP
Javascript
// 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.void pushZerosToEnd(int arr[], int n){    int 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 (int 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 program to test above functionint 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;}
#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 program to push zeroes to back of array */import java.io.*; class PushZero{    // Function which pushes all zeros to end of an array.    static void pushZerosToEnd(int arr[], int n)    {        int 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 (int 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 function to check for above functions*/    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]+" ");    }}/* This code is contributed by Devesh Agrawal */
# Python3 code to move all zeroes# at the end of array # Function which pushes all# zeros to end of an array.def pushZerosToEnd(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    for i in range(n):        if arr[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.    while count < n:        arr[count] = 0        count += 1         # Driver codearr = [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# program to push zeroes to back of array */using System; class PushZero{    // Function which pushes all zeros    // to end of an array.    static void pushZerosToEnd(int []arr, int n)    {        // Count of non-zero elements        int count = 0;                 // Traverse the array. If element encountered is        // non-zero, then replace the element        // at index â..countâ.. with this element        for (int 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 â..countâ.. is set as index of first 0.        // Make all elements 0 from count to end.        while (count < n)        arr[count++] = 0;    }         // Driver function    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] +" ");    }}/* This code is contributed by Anant Agrawal */
<?php// A PHP program to move all// zeroes at the end of array // Function which pushes all// zeros to end of an array.function pushZerosToEnd(&$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?>
<script>// A JavaScript program to move all zeroes at the end of array // Function which pushes all zeros to end of an array.function pushZerosToEnd(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>
Array after pushing all zeros to end of array :
1 9 8 4 2 7 6 9 0 0 0 0 
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 number of elements in input array.Auxiliary Space: O(1) 
YouTubeGeeksforGeeks507K subscribersMove all zeroes to end of array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0jXTju134Hw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
surbhityagi15
adityakhosla0
deadmarshal
Amazon
Bloomberg
Linkedin
Paytm
Samsung
SAP Labs
Arrays
Paytm
Amazon
Samsung
SAP Labs
Linkedin
Bloomberg
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Queue | Set 1 (Introduction and Array Implementation)
Array of Strings in C++ (5 Different Ways to Create)
Find the Missing Number
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find Second largest element in an array