Problem:


Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap



Sample input:
xyz
4


Sample output:
aya

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    S = input()
    K = int(input())
    ans = ''
    for s in S:
        if s=='a':
            ans += s
        else:
            if 123 - ord(s) <= K:
                ans += 'a'
                K -= 123 - ord(s)
            else:
                ans += s
    if K > 0:
        ans = ans[:-1] + (chr(ord(ans[-1]) + K%26))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
s = input()
k = int(input())
ans = ""
n = len(s)
for p, i in enumerate(s):
    if p == n - 1:
        ans += chr((ord(i) - 97 + k) % 26 + 97)
        break
    if (cost := (123 - ord(i)) % 26) <= k:
        ans += "a"
        k -= cost
    else:
        ans += i
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
from math import sqrt
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

S = input()
K = getN()
alpha = 'abcdefghijklmnopqrstuvwxyz'
ans = ''
# ループさせてaにできるならする
# できないなら持ち越し
for i in range(len(S) - 1):
    roop = (26 - alpha.index(S[i])) % 26
    if K >= roop:
        K -= roop
        ans += 'a'
    else:
        ans += S[i]

# 最後の一文字について
ans += alpha[(alpha.index(S[-1]) + K) % 26]
print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    s = list(input())
    k = int(readline())
    l = len(s)
    rem = k

    for i in range(l):
        char = s[i]
        diff = (ord("z") - ord(s[i]) + 1) % 26
        if rem >= diff:
            rem -= diff
            s[i] = "a"

    rem = rem % 26
    s[l - 1] = chr(ord(s[l - 1]) + rem)
    print("".join(s))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=input()
k=int(input())
n=len(s)
ans=""
for i in range(n):
    if i<n-1:
        if s[i]=="a":
            ans+="a"
        else:
            t=123-ord(s[i])
            if k>=t:
                ans+="a"
                k-=t
            else:
                ans+=s[i]
    if i==n-1:
        tt=(ord(s[i])-97+k)%26
        ans+=chr(tt+97)
print(ans)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
l = "abcdefghijklmnopqrstuvwxyz"
ans = ""
for i in range(len(s) - 1):
    num = (26 - l.index(s[i])) % 26
    if k >= num:
        ans += "a"
        k -= num
    else:
        ans += s[i]
ans += l[(l.index(s[-1]) + k) % 26]
print(ans)

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq

s = input()
l = len(s)
k = ni()
def aind(w):
    if w=="a":
        ret = 0
    else:
        ret = 26 - (ord(w) - ord("a"))
    return ret
ans = []
for i in range(l-1):
    if aind(s[i]) <=k:
        ans.append("a")
        k-=aind(s[i])
    else:
        ans.append(s[i])

idx =(ord(s[-1]) - ord("a") +k%26)%26 +ord("a")
ans.append( chr(idx) )
print("".join(ans))

Submission status: Accepted

Solution code:
string = input()
k = int(input())
ans = list(string)

alpha = "abcdefghijklmnopqrstuvwxyz"
alpha_to_num = {}
for i in range(26):
    alpha_to_num[alpha[i]] = i
    
for i, s in enumerate(ans):
    if s == "a":
        continue
    pos = alpha_to_num[s]
    kk = 26 - pos
    if kk > k:
        continue
    k -= kk
    ans[i] = "a"
    
pos = alpha_to_num[ans[-1]]
new_pos = (k + pos) % 26
ans[-1] = alpha[new_pos]
print("".join(ans))

Submission status: Accepted

Solution code:
s = input()
K = int(input())
alpha = "abcdefghijklmnopqrstuvwxyz"
inv_alpha = "azyxwvutsrqponmlkjihgfedcb"
D = {inv_alpha[i]: i for i in range(26)}
n = len(s)
for i in range(n):
  if i == n - 1:
    x = K % 26
    print(alpha[(26-D[s[i]]+x)%26], end = '')
  else:
    if K >= D[s[i]]:
      K -= D[s[i]]
      print('a', end = '')
    else:
      print(s[i], end = '')
print()

Submission status: Accepted

Solution code:
S = input()
K = int(input())

rest = K
oz = ord('z')
oa = ord('a')
ans = list(S)

for ci in range(len(S)):
    if S[ci] == 'a':
        continue
    
    check = oz - ord(S[ci]) + 1
    if rest >= check:
        ans[ci] = 'a'
        rest -= check

if rest >= 0:
    for i in range(rest%26):
        if oz == ord(ans[-1]):
            ans[-1] = 'a'
        else:
            ans[-1] = chr(ord(ans[-1])+1)
    
print("".join(ans))

Submission status: Accepted

Solution code:
s=input()
k=int(input())
n=len(s)
i=0
ans=""
while i<n:
    if i!=n-1:
        if s[i]=="a":
            ans+="a"
            #print(ord(s[i]),123-ord(s[i]),k)
        elif k>=123-ord(s[i]):
            ans+="a"
            k-=(123-ord(s[i]))
            #print(ord(s[i]),123-ord(s[i]),k)
        else:
            ans+=s[i]
            #print(ord(s[i]),123-ord(s[i]),k)
    else:
        if k>=123-ord(s[i]):
            k-=(123-ord(s[i]))#一旦aにする
            k=k%26
            ans+=chr(97+k)
        else:
            ans+=chr(ord(s[i])+k)
        
    i+=1
print(ans)

Submission status: Accepted

Solution code:
s = input()
K = int(input())

ans = []
for ch in s:
    v = ord("a") + 26 - ord(ch)
    if ch != "a" and v <= K:
        K -= v
        ans.append("a")
    else:
        ans.append(ch)

if K > 0:
    ans[-1] = chr(ord(ans[-1]) + K % 26)
print("".join(ans))

Submission status: Accepted

Solution code:
s=input()
K = int(input())
c = []
for i in range(len(s)):
    if s[i]=='a':
        c.append(0)
    else:
        c.append(123-ord(s[i]))
for i in range(len(s)):
    if c[i] <= K:
        K -= c[i]
        c[i]=0
    else:
        continue
if K >0 and c[-1]==0:
    c[i]+= K%26
else:
    c[i] = (-c[i] +K)%26
si = ''
for i in range(len(c)-1):
    if c[i]==0:
        si += 'a'
    else:
        si += s[i]
si += chr(97+c[-1])
print(si)

Submission status: Accepted

Solution code:
from bisect import *
S = list(str(input()))
K = int(input())

alp = list("abcdefghijklmnopqrstuvwxyz")

for i in range(len(S)):
  b = bisect_left(alp,S[i])

  if i == len(S)-1:
    S[i] = alp[(b+K)%26]
  elif b == 0:
    continue
  elif 26 - b <= K:
    K -= (26 - b)
    S[i] = "a"
  if K == 0:
    break
  
print("".join(S))

Submission status: Accepted

Solution code:
def main():
    import sys
    from collections import defaultdict

    def input(): return sys.stdin.readline().rstrip()

    s = input()
    n = len(s)
    k = int(input())
    for i in range(n):
        tmp = (ord('a')-ord(s[i]))%26
        if tmp > k:
            continue
        k -= tmp
        s = s[:i]+'a'+s[i+1:]
    s = s[:-1]+chr((ord(s[-1])+k%26-ord('a'))%26+ord('a'))
    print(s)

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s,k=open(0)
k=int(k)
*s,t=s
for q in s:
 if(p:=(123-ord(q))%26)<=k:t+="a";k-=p
 else:t+=q
print(t[1:-1]+chr((ord(t[-1])-97+k)%26+97))

Submission status: Accepted

Solution code:
s,k,t=input(),int(input()),""
for q in s:
 if(p:=(123-ord(q))%26)<=k:t+="a";k-=p
 else:t+=q
print(t[:-1]+chr((ord(t[-1])-97+k)%26+97))

Submission status: Accepted

Solution code:
s, k, t = input(), int(input()), ""
for q in s:
    if (p := (123 - ord(q)) % 26) <= k:
        k -= p
        t += "a"
    else:
        t += q
print(t[:-1] + chr((ord(t[-1]) - 97 + k) % 26 + 97))

Submission status: Accepted

Solution code:
s=list(input())

k=int(input())

ans = []

for alf in s:
    if alf == 'a':
        ans.append('a')
    else:
        if 123 - ord(alf) <= k:
            k -= 123 - ord(alf)
            ans.append('a')
        else:
            ans.append(alf)
if 0 < k:
    amari = (ord(ans[-1])-97+k)%26
    ans[-1] = chr(amari+97)
    
print(''.join(map(str,ans)))

Submission status: Accepted

Solution code:
s = input()
k = int(input())

asc = [0] * len(s)
for i in range(len(s)):
    asc[i] = ord(s[i]) - ord("a")
i = 0
for i in range(len(s)):
    if 26 - asc[i] <= k and asc[i] != 0:
        x = 26 - asc[i]
        asc[i] = 0
        k -= x
if k > 0:
    asc[-1] += k % 26
for i in range(len(s)):
    asc[i] += ord("a")
    asc[i] = chr(asc[i])
print("".join(asc))

Submission status: Accepted

Solution code:
def main():
    s = list(input())
    k = int(input())

    ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
    D = dict(zip(ascii_lowercase,list(range(0,len(ascii_lowercase)))))

    n = len(ascii_lowercase)

    for i in range(0,len(s)):
        j = D[s[i]]
        if j != 0 and 26 -j <= k:
            k -= (26-j)
            s[i] ='a'

    if k >0:
        j = (D[s[-1]] + k%26)%26
        s[-1] = ascii_lowercase[j]
    print(''.join(s))

main()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = list(SS())
    K = I()

    # 左からaにしていって、余ったKを一番右に突っ込む
    for i in range(len(s) - 1):
        diff = (ord('a') - ord(s[i])) % 26
        if K >= diff:
            K -= diff
            s[i] = 'a'

    if K > 0:
        s[-1] = chr((ord(s[-1]) - ord('a') + K) % 26 + ord('a'))
    
    print(''.join(s))

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
s = input()
K = int(input())
k = K

ans = ""
for i in range(len(s)-1):
    if(s[i] == "a"):
        ans += s[i]
        continue
    if(ord(s[i])+k >= ord("z")+1):
        ans += "a"
        k -= ord("z")+1-ord(s[i])
    else:
        ans += s[i]

a = ord(s[-1])+k%26
if(a > ord("z")):
    a -= 26
ans += chr(a)
    
print(ans)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
l=list(s)

for i in range(len(s)):
  f=(-ord(s[i])+ord("z")+1)%26
  if f<=k:
    l[i]="a"
    k-=f

k=k%26
a=ord(l[-1])+k 
if a> ord("z"):a-=26
l[-1]=chr(a)
print("".join(l))

Submission status: Accepted

Solution code:
s = input()
l = len(s)
n = int(input())
ans = ["A"]*l
for i in range(l-1):
  if s[i]=="a":
    ans[i]="a"
    continue
  temp = ord("z")-ord(s[i])+1
  if temp <= n:
    n-=temp
    ans[i]="a"
  else:
    ans[i]=s[i]

last = ord(s[l-1])+n
#print(last)
while last>ord("z"):
  last-=26
ans[l-1]=chr(last)
print("".join(ans))

Submission status: Accepted

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

s = list(input())
k = INT()

i = 0
while k > 0:
    tmp = ord(s[i]) - ord('a')
    if i < len(s) - 1:
        if tmp != 0 and 26 - tmp <= k:
            k -= 26 - tmp
            s[i] = 'a'
        i += 1
    else:
        s[i] = chr((tmp+k)%26 + ord('a'))
        k = 0

print(''.join(s))

Submission status: Accepted

Solution code:
from string import ascii_lowercase

def main():
    s = list(input())
    K = int(input())
    for i, c in enumerate(s):
        num = ord(c) - ord("a")

        if num > 0 and K - (26-num) >= 0:
            s[i] = "a"
            K -= (26-num)

    num = ord(s[-1]) - ord("a")
    last = (num + K)%26
    s[-1] = ascii_lowercase[last]
    print("".join(s))

        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s=list(input())
k=int(input())
for i in range(len(s)):
    if i==len(s)-1:
        s[-1]=chr((ord(s[i])-97+k)%26+97)
        break
    if s[i]=='a':
        continue
    if 123-ord(s[i])<=k:
        k-=123-ord(s[i])
        s[i]='a'
print(*s,sep='')

Submission status: Accepted

Solution code:
S = list(input())
K = int(input())

for i, s in enumerate(S):
    if s == "a":
        pass
    elif ord('z') - ord(s) + 1 <= K:
        S[i] = 'a'
        K -= ord('z') - ord(s) + 1

K %= 26
S[-1] = chr((ord(S[-1]) - ord('a') + K) % 26 + ord('a'))

print("".join(S))

Submission status: Accepted

Solution code:
s = input()
k = int(input())
ans = ""
for i in s:
    if k >= (123 - ord(i)) % 26:
        k -= (123 - ord(i)) % 26
        ans += "a"
    else:
        ans += i
print(ans[:-1] + chr((ord(ans[-1]) - 97 + k) % 26 + 97))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
A = 'abcdefghijklmnopqrstuvwxyz'
Da = {a:i for i,a in enumerate(A)}

c = 0
for i in range(len(s)):
    if s[i]!='a' and 26-Da[s[i]]<=k:
        k -= 26-Da[s[i]]
        s[i] = 'a'
if k:
    s[i] = A[Da[s[i]]+k%26]
print("".join(s))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
t = list(map(lambda x:ord(x)-ord("a"),s))
 
for i in range(len(t)):
  diff = 26-t[i]
  if diff != 26 and diff <= k: 
    t[i]+=diff
    k-=diff
t[-1]+=k
 
u = "".join(list(map(lambda x:chr((x%26+ord("a"))),t)))
print(u)

Submission status: Accepted

Solution code:
S = input().strip()
K = int(input())

ans = ""
for i, s in enumerate(S):
    if i == len(S) - 1:
        if ord(s) + K <= ord("z"):
            ans += chr(ord(s) + K)
        else:
            ans += chr(ord("a") + (ord(s) + K - ord("z") - 1) % 26)
    elif s == "a":
        ans += "a"
        continue
    elif ord("z") + 1 - ord(s) <= K:
        ans += "a"
        K -= (ord("z") + 1 - ord(s))
    else:
        ans += s

print(ans)

Submission status: Accepted

Solution code:
A = {i-97:chr(i) for i in range(97,123)}
B = {v:k for k,v in A.items()}
s = list(input().strip())
K = int(input())
for i in range(len(s)-1):
    if s[i]!="a" and K>=26-B[s[i]]:
        K -= (26-B[s[i]])
        s[i]="a"
k = K%26
ind = (B[s[-1]]+k)%26
s[-1] = A[ind]
print("".join(s))

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

s = list(input())
k = inp()
n = len(s)
nxa = ord('z') + 1

for i,x in enumerate(s):
    if x == 'a':
        continue
    rem = nxa - ord(x)
    if rem <= k:
        s[i] = 'a'
        k -= rem
if k > 0:
    s[-1] = chr(ord('a') + (ord(s[-1])-ord('a')+k)%26)
print(''.join(s))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

a=ord('a')
S=list(map(lambda x:ord(x)-a,input()))
K=int(input())
ans=[]
for x in S:
    if x==0:
        ans.append('a')
    elif 26-x<=K:
        ans.append('a')
        K-=26-x
    else:
        ans.append(chr(x+a))
if K>0:
    ans[-1]=chr((ord(ans[-1])-a+K)%26+a)
print(''.join(ans))

Submission status: Accepted

Solution code:
S = input()
K = int(input())

def ctoi(c):
    return ord(c) - ord('a')
def toa(c):
    i = ctoi(c)
    return (26-i)%26

ans = ''
for c in S:
    if len(ans)+1 == len(S):
        ans += chr((ctoi(c) + K)%26 + ord('a'))
    else:
        to = toa(c)
        if to <= K:
            ans += 'a'
            K -= to
        else:
            ans += c
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, deque, Counter
import math

# import copy
from bisect import bisect_left, bisect_right
import heapq

# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline

getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = 10 ** 20
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)


def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD


def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD


def kaijyo(n):
    ret = [1]
    for i in range(1, n + 1):
        ret.append((ret[-1] * i)% MOD)
    return ret


def solve():
    s = getS()
    k = getN()

    sn = [ord(i) - ord("a") for i in s]
    for i, c in enumerate(sn):
        if c != 0:
            if k >= 26 - c:
                k -= 26 - c
                sn[i] = 0

    sn[-1] = (sn[-1] + k) % 26

    # print(sn)

    print("".join([chr(i + ord("a")) for i in sn]))



def main():
    n = getN()
    for _ in range(n):
        solve()


if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
S = list(input())[: -1]
K = int(input())
a = ord("a")
N = len(S)
for i in range(N):
  x = ord(S[i])
  if K >= (a - x) % 26:
    K -= (a - x) % 26
    S[i] = "a"
S[-1] = chr((ord(S[i]) - a + K % 26) % 26 + a)
print("".join(S))

Submission status: Accepted

Solution code:
li_s = list(input())
k = int(input())
z = ord('z')
ans = ''
for i in range(len(li_s)):
    if i < len(li_s) - 1 and li_s[i] == 'a':
        ans += 'a'
    elif i < len(li_s)-1 and k-(z-ord(li_s[i])+1) >= 0:
        k -= z-ord(li_s[i])+1
        ans = ans + 'a'
    elif i < len(li_s)-1:
        ans = ans + li_s[i]
    elif i == len(li_s) - 1:
        p = ord(li_s[i])  + k
        p %= 26
        p += 78
        if 97 <= p:
            ans = ans + chr(p)
        else:
            ans = ans + chr(p+26)
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
n = len(s)
k = int(input())
t = [ord(s[i]) - 97 for i in range(n)]
for i in range(n):
    if k == 0:
        break
    x = 26 - t[i]
    if 0 < x % 26 <= k:
        k -= x
        s[i] = "a"
t[-1] = ord(s[-1]) - 97
if k > 0:
    s[-1] = chr((k + t[-1]) % 26 + 97)
print("".join(s))

Submission status: Accepted

Solution code:
s = list(input())
K = int(input())
a = ord('z') + 1
for i in range(len(s)-1):
    if s[i] == 'a':
        continue
    #print(K,a - ord(s[i]))
    if K >= (a - ord(s[i])):
        K -= a - ord(s[i])
        s[i] = 'a'
    #print(K,a - ord(s[i]))
i = len(s)-1
s[len(s)-1] = chr((ord(s[i])-ord('a') + K) % 26 + ord('a'))
print(''.join(s))

Submission status: Accepted

Solution code:
import string
S = input()
K = int(input())
LEN = len(S)
ans = ''
for pos, s in enumerate(S, 1):
    idx = string.ascii_lowercase.find(s)
    if pos < LEN:
        if idx > 0 and 26-idx <= K:
            ans += 'a'
            K -= (26 - idx)
        else:
            ans += s
    else:
        # 残りのKをすべて消費する
        ans += string.ascii_lowercase[(idx + K)%26]

print(ans)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    S = list(in_s())
    N = len(S)
    K = in_n()

    ac = ord('a') + 26
    zc = ord('z')

    for i in range(N):
        if S[i] != 'a':
            nc = ord(S[i])
            if ac - nc <= K:
                S[i] = 'a'
                K -= ac - nc

    if K != 0:
        tc = S[-1]
        S[-1] = chr(((ord(tc) - ord('a')) + K % 26) % 26 + ord('a'))

    print(''.join(S))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s,K = open(0).read().split()
K = int(K)
dista = [(123 - ord(x)) % 26 for x in s]
sa = sum(dista)
if K >= sa:
    print('a'*(len(s)-1)+chr(97+(K-sa)%26))
else:
    ans = []
    count = K
    for i in range(len(s)):
        if count >= dista[i]:
            ans.append('a')
            count -= dista[i]
        else:
            ans.append(s[i])
    if ans[-1] == 'a':
        ans[-1] = chr(97+(count%26))
    else:
        ans[-1] = chr(ord(ans[-1])+count)
    print(''.join(ans))

Submission status: Accepted

Solution code:
s = input()
K = int(input())

rlt = ''

for i in range(len(s)-1):
  c = (26-ord(s[i])+ord('a'))%26
  if K >= c:
    rlt += 'a'
    K -= c
  else:
    rlt += s[i]
    
rlt += chr((K + ord(s[-1]) - ord('a'))%26 + ord('a'))
print(rlt)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
t = list(map(lambda x:ord(x)-ord("a"),s))

for i in range(len(t)):
  diff = 26-t[i]
  if diff != 26 and diff <= k: 
    t[i]+=diff
    k-=diff
t[-1]+=k

u = "".join(list(map(lambda x:chr((x%26+ord("a"))),t)))
print(u)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
t = list(map(lambda x:ord(x)-ord("a"),s)) #a-zを0-25に正規化

for i in range(len(t)):
  diff = 26-t[i] #aになるまでの差
  if diff != 26 and diff <= k: 
    t[i]+=diff
    k-=diff
  else:
    continue

t[-1]+=k #k余りを一番最後に足す

u = "".join(list(map(lambda x:chr((x%26+ord("a"))),t)))
print(u)

Submission status: Accepted

Solution code:
s = input()
K = int(input())

for i,c in enumerate(s):
	x = (ord('z')-ord(c)+1)%26
	if x <= K:
		s = s[:i]+'a'+s[i+1:]
		K -= x

print(s[:-1]+chr((ord(s[-1])-ord('a')+K)%26+ord('a')))

Submission status: Accepted

Solution code:
s=input()
k=int(input())
lens=len(s)
alp="azyxwvutsrqponmlkjihgfedcb"

ans=[]
for i in range(lens):
    d=alp.index(s[i])
    if k>=d:
        k-=d
        ans.append("a")
    else:
        ans.append(s[i])

las=ans.pop()
alp="abcdefghijklmnopqrstuvwxyz"
ans.append(alp[(alp.index(las)+k)%26])

print("".join(ans))

Submission status: Accepted

Solution code:
s, k = input(), int(input())

ans = []
a = ord('z') + 1
for i in s:
    if a - ord(i) <= k and i != 'a':
        k -= a - ord(i)
        ans.append(ord('a'))
    else:
        ans.append(ord(i))
ans[-1] += k % 26
if ans[-1] >= a:
    ans[-1] -= 26
print(*map(chr, ans), sep='')

Submission status: Accepted

Solution code:
s, k = input(), int(input())

ans = []
a = ord('z') + 1
for i in s:
    if k == 0:
        ans.append(ord(i))
    elif a - ord(i) <= k and i != 'a':
        k -= a - ord(i)
        ans.append(ord('a'))
    else:
        ans.append(ord(i))
ans[-1] += k % 26
if ans[-1] >= a:
    ans[-1] -= 26
print(*map(chr, ans), sep='')

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
s = input()
k = int(input())
n = len(s)
ans = []
# kを減らしていく。もし、aまで戻せるならaまで進めてk をその分減らす。
for i in range(n):
    if s[i] == "a":
        ans.append("a")
    elif 123 - ord(s[i]) <= k:
        ans.append("a")
        k -= 123 - ord(s[i])
    else:
        ans.append(s[i])
# print(k)
k %= 26  # 26で割ったあまりに落とす
ans[-1] = chr((ord(ans[-1]) + k - 97) % 26 + 97)
print("".join(ans))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    s = list(input())
    N = len(s)
    K = int(input())
    i = 0
    while K > 0:
        if i == N-1:
            num = ord(s[i])+K%26
            if num > ord('z'):
                num -= 26
            s[i] = chr(num)
            break
        else:
            if s[i] != 'a':
                num = 26-ord(s[i])+ord('a')
                if  num <= K:
                    s[i] = 'a'
                    K -= num
            i += 1
    print(''.join(s))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)
alph_map = {chr(ord('a') + i): (26 - i) % 26 for i in range(26)}
for i in range(n):
    if k >= alph_map[s[i]]:
        k -= alph_map[s[i]]
        s[i] = 'a'
if k > 0:
    s[n-1] = chr((ord(s[n-1]) + k % 26) % 123)
print(''.join(s))

Submission status: Accepted

Solution code:
S = input()
K = int(input())

ans = ""
for s in S:
    if s == "a":
        ans += s
    elif 123-ord(s) <= K:
        ans += "a"
        K -= 123-ord(s)
    else:
        ans += s
if K > 0:
    ans = ans[:-1] + chr((ord(ans[-1])-97+K)%26+97)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)


    def calc_rotate_min(L, rotate):
        n = len(L)
        for i in range(n):
            # print(i, L, rotate)
            if rotate == 0:
                return
            if i == n - 1:
                # この文字をグルグルするしかない
                L[i] = (L[i] + rotate % 26) % 26
                return
            if L[i] != 0 and 26 - L[i] <= rotate:
                rotate -= (26 - L[i])
                L[i] = 0    # 'a' にする


    
    s = input()
    k = ii()
    L = list(map(lambda x: ord(x)-ord('a'), s))
    calc_rotate_min(L, rotate=k)
    
    for num in L:
        print(chr(num+ord('a')), end='')
    print('')



if __name__ == "__main__":
    main()