Given an array, that has zero. Move all the zero at the end, but maintain the relative order of other elements.

Example:

array = [3, 4, 0, 5, 6, 0 , 7, 1, 0, 3]

Output:

[3, 4, 5, 6, 7, 1, 3, 0, 0, 0]

The solution is very simple. We take 2 loops.
In the first loop, we shift all the elements that are not equal to 0.
Then in the second loop, we insert the number of 0’s required at the end.

Solution in C++

#include<iostream>
#include<vector>

using namespace std;

void shift_number_of_zeros(vector<int> &num)
{
	int j = 0;
	for(int i = 0 ; i < num.size(); i++)
	{
		if(num[i] != 0)
		{
			num[j++] = num[i];
		}
	}

	for(;j < num.size(); j++) 
	{
       	num[j] = 0;
   	}
}

int main()
{
	vector <int> nums= {3, 4, 0, 5, 6, 0 , 7, 1, 0, 3};

	shift_number_of_zeros(nums);

	cout<<"The result is "<<endl;
	for(int i = 0; i < nums.size(); i++ )
	{
		cout<<nums[i]<<" ";
	}
	cout<<endl;

	return 0;
}

Output:

The result is
3 4 5 6 7 1 3 0 0 0

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *