Last Updated: 13 Oct, 2022

Move Zero's to End

Easy

Problem statement

Given an array 'arr' of 'n' non-negative integers, your task is to move all the zeros to the end of the array while keeping the non-zero elements at the start of the array in their original order. Return the modified array.


Example :
Input: ‘n’ = 5, ‘arr’ = [1, 2, 0, 0, 2, 3]
Output: [1, 2, 2, 3, 0, 0]

Explanation: Moved all the 0’s to the end of an array, and the rest of the elements retain the order at the start.
Input Format:
The first line contains an integer ‘n’, the number of elements in the array ‘arr’.
The next line contains the 'n' space-separated integers of the array 'arr'.
Output Format:
The output contains the elements of the modified array separated by space.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function.

Approaches

01 Approach

Approach

 

We will maintain two-pointers first. Suppose we find a zero (say its index is 2) while traversing. In that case, this place should be occupied by the immediate following non-zero elements (so that order will be maintained for non-zero elements), so we will place a pointer here (at 2). We will try to find the next non-negative integer using another pointer; once it is found, zero places (2nd index) have to be occupied by this non-negative number, and the non-negative number will be occupied by zero.
 

Algorithm: 
 

  • Initialize an integer ‘j = 0’
  • Iterate from 0 to ‘n’ with iterator ‘i’
    • If ‘a[i] != 0’ then update ‘a[j++] = a[i]’
  • Iterate till ‘j < n’
    • Set ‘a[j] = 0’
  • Return ‘a’