Push Zeroes To End

 

You have been given a random integer array/list(ARR) of size N. You have been required to push all the zeros that are present in the array/list to the end of it. Also, make sure to maintain the relative order of the non-zero elements.

Sample Input 1:
6
2 0 0 2 3 0
Sample Output 1:
Updated Array -> 
2 2 3 0 0 0 

import java.util.Scanner;

public class PushZeros {

	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		int n=s.nextInt();
		int a[]=new int[n];
		for(int i=0;i<n;i++)
		{
			a[i]=s.nextInt();
		}
		
		pushZerosAtEnd(a);
		print(a);

	}
	
	public static void print(int a[])
	{
		System.out.println("Updated Array -> ");
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+" ");
		}

	}

	public static void pushZerosAtEnd(int[] arr) {
		
		int l = arr.length;
		int k=0;
		for(int i=0;i<l;i++)
		{
			if(arr[i]!=0)
			{
				arr[k]=arr[i];
				k++;
			}
		}
		while(k<l)
		{
			arr[k]=0;
			k++;
		}
}
}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern