In this

**HackerEarth Smallest number problem solution,**You are given a string S that represents a number. This string consists of the following characters only:1

2

3

You can perform the following operation:

- Swap any two adjacent characters only if the absolute difference between the characters is 1.

Your task is to determine the smallest number that can be formed by using the provided operation. You can perform this operation any number of times (possibly zero).

## HackerEarth Smallest number problem solution.

`#include<bits/stdc++.h>`

#define int long long int

using namespace std;

void solve(){

int n;

cin >> n;

assert(1 <= n and n <= 100000);

string s;

cin >> s;

int flag = -1;

int cnt_1 = 0;

int cnt_2 = 0;

for(int i = 0 ; i < n ; i++){

assert('1' <= s[i] and s[i] <= '3');

if(flag == -1 and s[i] == '1') cnt_1++;

if(s[i] == '3' and flag == -1) flag = i;

if(s[i] == '2') cnt_2++;

}

string answer = "";

while(cnt_1--) answer += '1';

while(cnt_2--) answer += '2';

if(flag != -1)

{

while(flag < n)

{

if(s[flag] == '2'){}

else answer += s[flag];

flag++;

}

}

cout << answer << endl;

}

signed main(){

ios_base::sync_with_stdio(false);

cin.tie(NULL);

int t;

cin >> t;

assert(1 <= t and t <= 10);

while(t--){

solve();

}

}

### Second solution

`t = int(input())`

while t > 0:

t -= 1

input()

s = input()

pre = s[:s.find('3')]

suf = s[s.find('3'):]

pre += ''.join(x for x in suf if x == '2')

suf = ''.join(x for x in suf if x != '2')

print(''.join(sorted(pre)) + suf)

## 0 Comments