Problem:


Score : 300 points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 \leq |S| \leq 26

S is a diverse word.

Input

Input is given from Standard Input in the following format:

S

Output

Print the next word that appears after S in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx



Sample input:
atcoder


Sample output:
atcoderb

Submission status: Accepted

Solution code:
s = input()+chr(ord("a")-1)
ans = -1
for i in range(len(s)):
    t = s[:~i]
    dif = set(map(chr,range(ord(s[~i])+1,123))) - set(t)
    if dif:
        ans = t + min(dif)
        break
print(ans)

Submission status: Accepted

Solution code:
def solve():
    S = input()

    if len(S) < 26:
        for a in [chr(ord("a")+i) for i in range(26)]:
            if a in S:
                continue
            print(S+a)
            return


    for i in range(26):
        for a in [chr(j) for j in range(ord(S[-1-i]), ord("z")+1)]:
            if a in S[:len(S)-i]:
                continue
            print(S[:len(S)-i-1]+a)
            return

    else:
        print(-1)

solve()

Submission status: Accepted

Solution code:
s = input()
last = s[-1]
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
n = len(ascii_lowercase)

for moji in ascii_lowercase:
    if moji not in s:
        s += moji
        print(s)
        exit()

sl = list(s)
for i in range(len(s)-1, -1,-1):
    idx = ascii_lowercase.index(s[i])
    for j in range(idx,n):
        if ascii_lowercase[j] not in sl:
            sl[i] = ascii_lowercase[j]
            print(''.join(sl))
            exit()
    sl.pop()

if not sl:
    print(-1)

Submission status: Accepted

Solution code:
from collections import defaultdict
s = input()
n = len(s)
ans = -1

if len(s) < 26:
    alphabet_ls = [chr(i) for i in range(97, 97+26)]
    alphabet_dict = defaultdict(int)
    for i in range(n):
        alphabet_dict[s[i]] = 1
    for alphabet in alphabet_ls:
        if alphabet_dict[alphabet] == 0:
            ans = s + alphabet
            break

else:
    stock_ls = []
    for i in range(25,-1,-1):
        now = s[i]
        greater = []
        for stock in stock_ls:
            if now < stock:
                greater.append(stock)
        if greater:
            replacer = min(greater)
            ans = s[:i] + replacer
            break
        else:
            stock_ls.append(s[i])
print(ans)

Submission status: Accepted

Solution code:
S = input()
alphabets = [chr(x + ord('a')) for x in range(26)]
if len(S) < 26:
  n = min(set(alphabets) - set(s for s in S))
  print(S+n)
else:
  current = 'a'
  done = False
  for i in range(26):
    if S[25-i] < current:
      n = min(s for s in S[25-i+1:] if s > S[25-i])
      #sub = [s for s in S[25-i:]]
      #sub.remove(n)
      print(S[:25-i] + n )#+ ''.join(sorted(s for s in sub)))
      done = True
      break
    else:
      current=S[25-i]
  if not done:
    print(-1)

Submission status: Accepted

Solution code:
s=input()
a=set(list(s))
for i in range(26):
  if chr(ord("a")+i) not in a:
    print(s+chr(ord("a")+i))
    exit()
ans=s
for i in range(26):
  for m in s[i+1:]:
    if ord(s[i])<ord(m):
      ans=s[:i]+m
if ans==s:
  print(-1)
else:
  print(ans)

Submission status: Accepted

Solution code:
s = list(input())
kouho = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
         "w", "x", "y", "z"]
for i in s:
    kouho.remove(i)
if kouho == []:
    kouho.append(s.pop(-1))
    for i in range(25):
        dum = s.pop(-1)
        for j in range(len(kouho)):
            if dum < kouho[j]:
                s.append(kouho[j])
                print("".join(s))
                exit()
        else:
            kouho.append(dum)
            kouho.sort()
    else:
        print(-1)
    print("".join(s))
else:
    s.append(kouho[0])
    print("".join(s))

Submission status: Accepted

Solution code:
S = input()
if S == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()

A = list("abcdefghijklmnopqrstuvwxyz")
if len(S) < 26:
    for i in A:
        if i not in S:
            print(S+i)
            exit()

for i in range(24,0,-1):
    if S[i] != max(S[i:]):
        B = [j for j in S[i+1:] if j > S[i]]
        print(S[:i]+min(B))
        exit()
print(A[A.index(S[0]) + 1])

Submission status: Accepted

Solution code:
import sys
s = input()

if len(s) < 26:
    for i in range(ord('a'), ord('z')+1):
        if not chr(i) in s:
            print(s+chr(i))
            break
elif s == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)
else:
    a = set()
    for i in range(26):
        a.add(s[25-i])
        for j in sorted(a):
            if s < s[:25-i]+j:
                print(s[:25-i]+j)
                sys.exit()

Submission status: Accepted

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
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
from functools import reduce
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 = input()
a = [0]*26

if len(s) != 26:
    for x in s:
        a[ord(x)-ord('a')] += 1
    for i in range(26):
        if a[i] == 0:
            tmp = i
            break
    ans = s + chr(ord('a')+tmp)
else:
    if s == "zyxwvutsrqponmlkjihgfedcba":
        ans = -1
    else:
        for i in range(len(s)-1, -1, -1):
            k = ord(s[i])-ord('a')
            j = 1
            while k + j < 26:
                if a[k+j] == 0:
                    j += 1
                else:
                    tmp = k + j
                    break
            else:
                a[k] += 1
                continue
            tmp2 = i
            break
        ans = s[:tmp2] + chr(tmp+ord('a'))
print(ans)

Submission status: Accepted

Solution code:
S = str(input())
N = len(S)
L = list(S)
L = set(L)
if N != 26: #含まないものがある
  for i in range(26):
    temp = chr(i+97)
    if temp not in L:
      ans = S+temp
      print(ans)
      exit()
M = []
All = [chr(97+i) for i in range(26)]
#print(All)
for i in range(25):
  now = 25-i
  M.append(S[now])
  if S[now] > S[now-1]:
    M.sort()
    for x in M:
      if x > S[now-1]:
        temp = x
        ans = S[:now-1]+temp
        print(ans)
        exit()
  
print(-1)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

S = list(input())
all_set = set([chr(97+i) for i in range(26)])

if len(S)<26:
    raw_set = set(S)
    lis = list(all_set - raw_set)
    lis.sort()
    S.append(lis[0])
    print(''.join(S))
else:
    can_use = set()
    p = S[-1]
    can_use.add(p)
    for i in range(24, -1, -1):
        nx = S[i]
        if ord(nx)<ord(p):
            for c in sorted(list(can_use)):
                if ord(nx)<ord(c):
                    break
            S = S[:i]+[c]
            print(''.join(S))
            break
        else:
            can_use.add(nx)
            p = nx
    else:
        print(-1)

Submission status: Accepted

Solution code:
S = input().strip()
if len(S)<26:
    for i in range(97,123):
        if chr(i) not in S:
            print(S+chr(i))
            break
else:
    flag = 0
    for i in range(24,-1,-1):
        if S[i]<S[i+1]:
            a = S[i]
            for j in range(25,i,-1):
                if S[j]>a:
                    print(S[:i]+S[j])
                    flag = 1
                    break
            if flag==1:break
    if flag==0:
        print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
s = input()
stock = [m for i in range(26) if (m := chr(ord("a") + i)) not in s]
if stock:
    print(s + stock[0])
else:
    for i in range(1, 26):
        if s[-i] > s[-1 - i]:
            print(s[:-1 - i] + min(j for j in s[-i:] if j > s[-1 - i]))
            break
        if i == 25:
            print(-1)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
s = readline().rstrip().decode('utf-8')
kijun = ord("a")
if len(s) == 26:
    if s == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
        exit()
    else:
        for i in range(26):
            res = s[i:]
            flag = True
            for j in range(len(res)-1):
                if ord(res[j]) < ord(res[j+1]):
                    flag = False
                    break
            if flag:
                ans = s[:i-1]
                res2 = []
                for j in res:
                    res2.append(ord(j))
                res2.sort()
                for j in res2:
                    if ord(s[i-1]) < j:
                        print(ans + chr(j))
                        exit()




for i in range(kijun,kijun+26):
    if chr(i) not in s:
        print(s+chr(i))
        exit()

Submission status: Accepted

Solution code:
s=str(input())
t=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
if len(s)!=26:
  s=list(s)
  for i in range(26):
    if t[i] not in s:
      s.append(t[i])
      break
  print("".join(s))
else:
  if "".join(s)=="zyxwvutsrqponmlkjihgfedcba":
    print(-1)
  else:
    a=[]
    for i in range(26):
      a.append(s[25-i])
      for j in a:
        if s<s[:25-i]+j:
          print(s[:25-i]+j)
          exit()

Submission status: Accepted

Solution code:
dic = [False for i in range(26)]
txt = input()
for i in txt:
  dic[ord(i) - 97] = True
for i in range(26):
  if not dic[i]:
    print(txt + chr(i + 97))
    break
else:
  for j in range(25):
    if txt[24 - j] < txt[25 - j]:
      
      last = txt[24-j] #以降の文字列を修正
      txt = txt[:24 - j]
      
      dic = [False for i in range(26)]
      for k in txt:
        dic[ord(k) - 97] = True
      txt += chr(dic[ord(last) - 96:].index(False) + ord(last) + 1)

      print(txt)
      break

  else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

S = list(input())
# while 1:
if len(S)==26:
    end = S[-1]
    lis = [end]
    for i in range(24, -1, -1):
        if ord(S[i])<ord(end):
            for s in lis:
                if ord(S[i])<ord(s):
                    S[i] = s
                    break
            S = S[:i+1]
            print(''.join(S))
            break
        else:
            lis.append(S[i])
            end = S[i]
    else:
        if S[0]=='z':
            print(-1)
        else:
            S = [chr(ord(S[0])+1)]
            print(S[0])
else:
    check = [0]*26
    for s in S:
        check[ord(s)-97] = 1
    for i in range(26):
        if not check[i]:
            S.append(chr(i+97))
            break
    print(''.join(S))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[27]:


S = input()


# In[28]:


ZtoA = "zyxwvutsrqponmlkjihgfedcba"
diff = sorted(list(set(ZtoA)^set(S)))
if len(S) < 26:
    print(S+diff[0])
else:
    if S == ZtoA:
        print(-1)
    else:
        for i in range(25):
            if S[i] < S[i+1]:
                k = i
        a = "z"
        for i in range(k+1,26):
            if S[k] < S[i]:
                a = min(a, S[i])
        print(S[:k]+a)


# In[ ]:

Submission status: Accepted

Solution code:
import sys
C = [0] * 26
S = input()
N = len(S)
for s in S:
    C[ord(s) - ord('a')] += 1
if N < 26:
    for i in range(26):
        if C[i] == 0:
            print(S + chr(i + ord('a')))
            sys.exit()
else:
    V = [S[N - 1]]
    i = N - 2
    while i >= 0:
        for v in V:
            if S[i] < v:
                print(S[:i] + v)
                sys.exit()
        V.append(S[i])
        V.sort()
        i -= 1
    print(-1)

Submission status: Accepted

Solution code:
import string
from itertools import permutations
S = input()

#%%
def next_permutation(a):
    """Generate the lexicographically next permutation inplace.

    https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
    Return false if there is no next permutation.
    """
    # Find the largest index i such that a[i] < a[i + 1]. If no such
    # index exists, the permutation is the last permutation
    for i in reversed(range(len(a) - 1)):
     if a[i] < a[i + 1]:
      break # found
    else: # no break: not found
     return False # no next permutation

    # Find the largest index j greater than i such that a[i] < a[j]
    j = next(j for j in reversed(range(i + 1, len(a))) if a[i] < a[j])

    # Swap the value of a[i] with that of a[j]
    a[i], a[j] = a[j], a[i]

    # Reverse sequence from a[i + 1] up to and including the final element a[n]
    a[i + 1:] = reversed(a[i + 1:])
    return True

#%%
alphabet = set(string.ascii_lowercase)

if len(S) < 26:
    s_diff = alphabet.difference(set(S))
    ans = S + min(s_diff)
elif S == "zyxwvutsrqponmlkjihgfedcba":
    ans = -1
else:
    T = list(S)
    next_permutation(T)
    ans = ''
    for i in range(len(S)):
        ans += T[i]
        if S[i] < T[i]:
            break

print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)

alp = [chr(i) for i in range(97, 97+26)]

if n < 26:
    for a in alp:
        if a not in s:
            print(s + a)
            exit()
else:
    i = 25
    while True:
        if i == 0:
            print('-1')
            exit()
        if s[i - 1] < s[i]:
            break
        i -= 1
    t = sorted(s[i-1:])
    idx = t.index(s[i-1]) + 1
    print(s[:i-1] + t[idx])

Submission status: Accepted

Solution code:
S=input()
A='abcdefghijklmnopqrstuvwxyz'
N=len(S)

ans='-1'
if N<26:
    for a in A:
        if a not in S:
            ans=S+a
            break
else:
    rs=S[::-1]
    i=1
    while i<26:
        srt=sorted(rs[:i+1])
        if srt[-1]!=rs[i]:
            ans=rs[i+1:][::-1]+srt[srt.index(rs[i])+1]
            break
        i+=1

print(ans)

Submission status: Accepted

Solution code:
s=input()
if len(s)<26:
    num=list(range(97,123))
    for i in range(len(s)):
        num.remove(ord(s[i]))
    print(s+chr(num[0]))
else:
    if s=="zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    else:
        for i in range(25):
            if ord(s[-1-i])>ord(s[-2-i]):
                str1=s[-2-i]
                num1=26-(2+i)
                break
        ans=123
        num3=ord(str1)
        for i in range(num1+1,26):
            num4=ord(s[i])
            if num3<num4:
                ans=min(ans,num4)
        print(s[:num1]+chr(ans))

Submission status: Accepted

Solution code:
def resolve():
    '''
    code here
    '''
    import string
    S = [item for item in input()]
    temp_abc = [item for item in string.ascii_lowercase]

    if len(S) < 26:
        for item in S:
            temp_abc.remove(item)
        res = ''.join(S) + temp_abc[0] 

    else:
        if S == temp_abc[::-1]:
            res = -1
        else:
            tail_inorder = []
            prev = 'a'
            cnt = 0
            for item in S[::-1]:
                if item >= prev:
                    tail_inorder += [item]
                    cnt += 1
                else:
                    break
                prev = item
            end_letter = S[-1*(cnt+1)]
            tail_inorder.sort()
            for item in tail_inorder:
                if end_letter < item:
                    res_end_letter = item
                    break

            res = S[:-1*(cnt+1)] + [res_end_letter]
    print(''.join(res)) if res != -1 else print(res)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
S=input()
S_list=list(S)
words=[chr(i) for i in range(97, 97+26)]

if S=='zyxwvutsrqponmlkjihgfedcba':
    print(-1)

else:
    if len(S)<=25:
        for word in words:
            if not word in S:
                S+=word
                break
        print(S)
    else:
        for n in range(1, 26):
            saisho = S_list[-n]
            N_f = words.index(saisho)
            saigo = S_list[-n - 1]
            N_l = words.index(saigo)
            if N_f < N_l:
                continue
            else:
                S_f = S_list[:-n - 1]
                S_l = S_list[-n:]
                S_l_new = sorted(S_l)
                new = []
                for number in S_l_new:
                    if words.index(number) > N_l:
                        new.append(number)
                        break
                S_f += new
                print(''.join(S_f))
                break

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
enum = enumerate
INF = 1001001001

import collections
import random

def linput(ty=int, cvt=list):
	return cvt(map(ty,input().split()))

def gcd(a: int, b: int):
	while b: a, b = b, a%b
	return a

def lcm(a: int, b: int):
	return a * b // gcd(a, b)

def dist(x1,y1,x2,y2):
	return abs(x1-x2)+abs(y1-y2)

def ran():
	vRan = [chr(i+ord("a")) for i in range(26)]
	random.shuffle(vRan)
	sr = "".join(vRan)
	print(sr)
	return sr

def main():
	S = input().rstrip()
	#S = ran()###
	#vS = [input().rstrip() for _ in [0,]*N]
	N = len(S)
	oA = ord("a")
	vD = [chr(i+oA) for i in range(26)]
	#vD += [".","#"]

	for d in vD:
		if d not in S:
			print(S+d)
			return
	
	if S=="".join(vD[::-1]):
		print(-1)
		return

	vQ = []
	vR = [ord(s) for s in S]
	vQ.append(vR.pop())
	
	while vR:
		r = vR.pop()
		nowq = INF
		for q in vQ:
			if q>r:
				nowq = min(nowq,q)
		if nowq<INF:
			vR.append(nowq)
			break
		vQ.append(r)
	
	res = "".join(chr(r) for r in vR)
	print(res)
	#sT = "No Yes".split()
	#print(sT[res])
	

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
import string
from itertools import permutations

S = input()
if len(S) == 26:
    if S == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
    else:
        for i in range(25, -1, -1):
            j = 0
            while chr(ord(S[i]) + j + 1) <= "z":
                j += 1
                if chr(ord(S[i]) + j) not in set(S[:i]):
                    print(S[:i] + chr(ord(S[i]) + j))
                    exit()
else:
    for c in string.ascii_lowercase:
        if c not in S:
            print(S + c)
            exit()

Submission status: Accepted

Solution code:
s=input()

alps="abcdefghijklmnopqrstuvwxyz"
if len(s)==26:
    if s=="zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    else:
        dels=[]
        for i in range(26):
            dels.append(s[25-i])
            for del_i in dels:
                if s<s[:25-i]+del_i:
                    print(s[:25-i]+del_i)
                    exit()
else:
    for alp in alps:
        if s.count(alp)==0:
            print(s+alp)
            exit()

Submission status: Accepted

Solution code:
import bisect
s=input()
n=len(s)
if n!=26:
  alp=[1]*26
  for i in s:
    alp[ord(i)-ord('a')]=0
  for i in range(26):
    if alp[i]:break
  ans=s+chr(ord('a')+i)
else:
  alp=[]
  for i in range(n-1,-1,-1):
    if bisect.bisect_left(alp,ord(s[i]))==len(alp):
      bisect.insort_left(alp,ord(s[i]))
    else:
      ans=s[:i]+chr(alp[bisect.bisect_left(alp,ord(s[i]))])
      break
  else:ans=-1
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():
    from string import ascii_lowercase

    s = input()
    if s == "zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    elif len(s) < 26:
        x = set(ascii_lowercase) - set(s)
        x = list(x)
        x.sort()
        print(s + x[0])
    else:
        for i in range(25, -1, -1):
            j = 0
            while chr(ord(s[i]) + j + 1) <= "z":
                j += 1
                if chr(ord(s[i]) + j) not in set(s[:i]):
                    return print(s[:i] + chr(ord(s[i]) + j))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict
from math import sqrt, factorial, gcd, ceil
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8')
import string
# string.ascii_lowercase

def solve():
    s = input()
    a = [x for x in s]

    if s == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
        return

    x = set(a)
    xd = []

    if len(s) == 26:
        while a[-2] > a[-1]:
            xd.append(a.pop())
        xd.append(a.pop())
        wtf = a.pop()
        xd.sort()
        for e in xd:
            if e > wtf:
                print(''.join(a) + e)
                return
    else:
        for e in string.ascii_lowercase:
            if e not in x:
                print(s + e)
                return
    
t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()


"""

azyxwvutsrqponmlkjihgfedcb

"""

Submission status: Accepted

Solution code:
import collections
s = input()


cnt = collections.Counter(s)
used = set(cnt.keys())
c = -1
if len(used) < 26:
    for i in range(26):
        if not chr(i+ord("a")) in used:
            c = chr(i+ord("a"))
            break
if c != -1:
    print(s+c)
else:
    if s == "zyxwvutsrqponmlkjihgfedcba":
        print("-1")
        exit()
    i = 25
    while i > 1 and s[i-1] > s[i]:
        i -= 1
    lused = sorted(s[i-1:])
    print(s[:i-1]+lused[lused.index(s[i-1])+1])

Submission status: Accepted

Solution code:
S = str(input())
l = [chr(i) for i in range(97,97+26)]

flag = True
for s in l:
  if s not in S:
    ans = S + s
    flag = False
    break
    
if flag:
  if S == 'zyxwvutsrqponmlkjihgfedcba':
    ans = -1
  else:
    while flag:
      num = ord(S[-1])
      S = S[:-1]
      for n in range(num+1, 123):
        if chr(n) not in S:
          ans = S + chr(n)
          flag = False
          break
    
print(ans)

Submission status: Accepted

Solution code:
s=input()

ans=""

if len(s)<26:
    cnt_alphabet=[0]*26

    for i in range(len(s)):
        cnt_alphabet[ord(s[i])-97]+=1
    
    moji=""
    for i in range(26):
        if cnt_alphabet[i]<1:
            moji=chr(i+97)
            break
    ans=s+moji

else:
    cnt=25
    
    for i in range(24,-1,-1):
        if ord(s[i])>ord(s[i+1]):
            cnt=i
        else:
            break
    
    if cnt==0:
        ans='-1'
    else:
        min_chr=ord('{')
        for m in s[cnt:]:
            if ord(m)>ord(s[cnt-1]):
                min_chr=min(min_chr,ord(m))
            
        ans=s[:cnt-1]+chr(min_chr)

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
d = defaultdict(int)
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
     'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

S = input()
if S == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()

if len(S) < 26:
    for x in S:
        d[x] += 1
    for x in a:
        if d[x] == 0:
            print(S+x)
            exit()
else:
    i = 25
    while S[i-1] > S[i]:
        i -= 1
    ss = sorted(list(S[i-1:]))
    t = S[i-1]
    print(S[:i-1] + ss[ss.index(t)+1])

Submission status: Accepted

Solution code:
S = input()
if len(S) <26:
    for i in range(97,97+26):
        if chr(i) in S:
            continue
        else:
            print(S+chr(i))
            exit()
else:
    for i in range(25,0,-1):
        s =S[:i]
        for j in range(97,97+26):
            if chr(j)>s[-1] and chr(j) not in s:
                print(s[:-1]+chr(j))
                exit()
print(-1)

Submission status: Accepted

Solution code:
from string import ascii_lowercase
S = input()
N = len(S)
if N < 26:
    for char in ascii_lowercase:
        if char in S: continue
        print(S + char)
        exit()
if S == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)
    exit()
for i in range(N - 1, -1, -1):
    for j in range(N - 1, i, -1):
        if S[i] < S[j]:
            print(S[:i] + S[j])
            exit()

Submission status: Accepted

Solution code:
s=input()
if len(s)<26:
    al=[chr(ord('a') + i) for i in range(26)]
    for i in al:
        if not(i in s):
            print(s+i)
            exit()
if s=="zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()
for i in range(25):
    if s[i]<s[i+1]:
        k=i
a="z"
for i in range(k+1,26):
    if s[k]<s[i]:
        a=min(a,s[i])
print(s[:k]+a)

Submission status: Accepted

Solution code:
# 8
import sys


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


INF = float('inf')


s = S()
alps = [chr(i) for i in range(ord('a'), ord('z') + 1)]
ans = -1
set_s = set(list(s))
# s の長さが 26 未満のとき
# 辞書順で s 以降の単語を探す
for c in alps:
    if c not in set_s:
        ans = s + c
        print(ans)
        break
# s の長さが 26 のとき
else:
    for i in reversed(range(len(s))):
        # i - 1 文字目までの s の アルファベットの集合
        set_now_s = set(list(s[:i]))
        for c in alps:
            if c > s[i] and c not in set_now_s:
                ans = s[:i] + c
                print(ans)
                exit()
    else:
        print(-1)

Submission status: Accepted

Solution code:
S = input()
if len(S) != 26:
  A = [0] * 26
  offset = ord('a')
  for s in S:
    A[ord(s)-offset] = 1
  print(S + chr(A.index(0)+offset))
elif S == 'zyxwvutsrqponmlkjihgfedcba':
  print(-1)
else:
  k = 25
  while S[k-1] > S[k]:
    k -= 1
  X = sorted(S[k-1:])
  print(S[:k-1] + X[X.index(S[k-1]) + 1])

Submission status: Accepted

Solution code:
from string import ascii_lowercase as T
S = input()
if len(S) != 26:
  A = [0] * 26
  offset = ord('a')
  for s in S:
    A[ord(s)-offset] = 1
  print(S + chr(A.index(0)+offset))
elif S == T[::-1]:
  print(-1)
else:
  k = 25
  while S[k-1] > S[k]:
    k -= 1
  x = S[k-1]
  Y = sorted(S[k-1:])
  print(S[:k-1] + Y[Y.index(x) + 1])

Submission status: Accepted

Solution code:
S = input()
N = len(S)
if N != 26:
    for i in range(26):
        c = chr(97 + i)
        if not c in S:
            print(S + c)
            exit()
li = []
for i in reversed(range(26)):
    li.append(S[i])
    if i == 0:
        print(-1)
        exit()
    if S[i-1] < S[i]:
        e = i - 1
        break
li.sort()
for x in li:
    if S[e] < x:
        print(S[:e] + x)
        exit()

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


s = input()
l = [chr(v) for v in range(ord("a"), ord("z")+1)]
l2 = {c:i for i,c in enumerate(l)}
def sub(s1, s2, used):
#     print(s1,s2,used)
    if not s1:
        if s2[0]=="z":
            return -1
        else:
            return l[l2[s2[0]]+1]
    if len(s1)+len(s2)<26:
        for i in range(26):
            if l[i] not in used:
                return s1+l[i]+s2
    else:
        if not s2:
            return sub(s1[:-1], s1[-1], set(s1[:-1]))
        for i in range(l2[s2[0]]+1, 26):
            if l[i] not in used:
                ans = s1+l[i]
#                 used.add(l[i])
#                 ans = ans + "".join(sorted([c for c in l if c not in used]))
                return ans
        used.remove(s1[-1])
        return sub(s1[:-1], s1[-1]+s2, used)
ans = sub(s, "", set(s))
print(ans)

Submission status: Accepted

Solution code:
import string


def solution(s):
    if len(s) == 0:
        for c in string.ascii_lowercase:
            if S[0] < c:
                print(c)
                return
        print(-1)
        return

    for c in string.ascii_lowercase:
        if len(s + c) == len(set(s + c)) and (s + c) > S:
            print(s + c)
            return
    solution(s[:-1])


if __name__ == "__main__":

    S = input()
    solution(S)

Submission status: Accepted

Solution code:
S = input()
alpha = [0] * 26
for s in S:
    alpha[ord(s) - 97] = 1

for i, value in enumerate(alpha):
    if value == 0:
        S = S + chr(i + 97)
        print(S)
        exit()

while len(S) > 1 or S[0] != 'z':
    idx = ord(S[-1]) - 97 + 1
    for i in range(idx, 26):
        if alpha[i] == 0:
            S = S[:-1] + chr(i + 97)
            print(S)
            exit()
    alpha[idx - 1] = 0
    S = S[:-1]

print(-1)

Submission status: Accepted

Solution code:
S = input()
if S == "zyxwvutsrqponmlkjihgfedcba":
  print(-1)
  exit()
if len(S) != 26:
  L = [0]*26
  for i in range(len(S)):
    L[ord(S[i])-97] = 1
  for i in range(26):
    if L[i] == 0:
      print(S + chr(97+i))
      exit()
else:
  B = []
  for i in reversed(range(26)):
    if ord(S[i]) > ord(S[i-1]):
      U = i
      M = i-1
      B += [ord(S[i])]
      break
    else:
      B += [ord(S[i])]
  B.sort()
  for i in B:
    if chr(i) > S[M]:
      print(S[:M] + chr(i))
      exit()

Submission status: Accepted

Solution code:
S=list(input())
N=len(S)
abc=list("abcdefghijklmnopqrstuvwxyz")
D={}
for a in abc:
    D[a]=0
idx={}
for i in range(26):
    idx[abc[i]]=i

for s in S:
    D[s]+=1
L=[]
for k,v in D.items():
    if v==0:
        L.append(k)

L=sorted(L)
if len(L)==0:
    lis=[]
    for i in range(25,-1,-1):
        s=S[i]
        lis.append(s)
        if i!=0:
            if idx[s]>idx[S[i-1]]:
                break
    if len(lis)==26:
        print(-1)
        exit()

    lis=sorted(lis)
    for l in lis:
        if idx[S[i-1]]<idx[l]:
            add=l
            break
    ans="".join(S[:i-1])+add
    print(ans)

        
else:
    print("".join(S)+L[0])
#yzxwvutsrqponmlkjihgfedcba