In this HackerEarth The smallest string problem solution You are given a string S which consists of lower case Latin letters and you need to perform the following operation exactly K times:
Select any character and replace it with its next character [‘a’ with ‘b’, ‘b’ with ‘c’…. ‘z’ with ‘a’].
You need to find the lexicographically smallest string after performing exactly K operations on string S.
HackerEarth The smallest string problem solution.
#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define endl "n"
#define test ll txtc; cin>>txtc; while(txtc--)
typedef long long int ll;
typedef long double ld;
int main() {
FIO;
test
{
ll n,k,ops; cin>>n>>k;
string s; cin>>s;
for(ll i=0;i+1<n;i++){
ops=('z'-s[i]+1)%26;
if(k>=ops){
s[i]='a';
k-=ops;
}
}
k%=26;
ops=(s[n-1]-'a');
ops+=k;
ops%=26;
s[n-1]=char('a'+ops);
cout<<s<<endl;
}
return 0;
}
Second solution
t = int(input())
while t > 0:
t -= 1
n, k = map(int, input().split())
s = list(input())
for i in range(n):
if (ord('z') - ord(s[i]) + 1) % 26 <= k:
k -= (ord('z') - ord(s[i]) + 1) % 26
s[i] = 'a'
k %= 26
s[-1] = chr(ord(s[-1]) + k if ord(s[-1]) + k <= ord('z') else ord(s[-1]) + k - 26)
print(''.join(s))