Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerEarth Smallest number problem solution

YASH PAL, 31 July 202415 February 2026
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

 

 

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)
 
 
coding problems solutions HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

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

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes