1102D. Balanced Ternary String - Codeforces Solution C++

  Problem Link : 1102D. Balanced Ternary String 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int

int main()
{
	int n;
	cin>>n;
	char arr[n];
	int zc=0,oc=0,tc=0;
	for(int i=0;i<n;i++)
	{
		cin>>arr[i];
		if(arr[i]=='0')
			zc++;
		else if(arr[i]=='1')
			oc++;
		else
			tc++;
	}
	int zreq=n/3 - zc;
	int oreq=n/3 - oc;
	int treq=n/3 - tc;
	zc=0,oc=0,tc=0;
	for(int i=0;i<n;i++)
	{
		if(arr[i]=='0')
		{
			if(zc < n/3)
				zc++;
			else
			{
				if(oreq > 0)
				{
					oreq--;
					arr[i]='1';
				}
				else
				{
					treq--;
					arr[i]='2';
				}
			}
		}
		else if(arr[i]=='2')
		{
			if(treq >= 0)
				continue;
			if(zreq>0)
			{
				zreq--;
				treq++;
				arr[i]='0';
			}
			else if(oreq > 0)
			{
				oreq--;
				treq++;
				arr[i]='1';
			}
		}	
		else
		{
			if(oreq>=0)
				continue;
			if(zreq > 0)
			{
				zreq--;
				oreq++;
				arr[i]='0';
			}
			else if(oc < n/3)
				oc++;
			else if(treq > 0)
			{
				treq--;
				oreq++;
				arr[i]='2';
			}
		}
	}

	for( char c : arr)
		cout<<c;

}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!