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:
#!/usr/bin/env python3
import sys, math, fractions, itertools, collections, copy, heapq


def solve(S: str):
    a = 'abcdefghijklmnopqrstuvwxyz'
    if len(S) != 26:
        for i in range(26):
            if not a[i] in S:
                print (*S, sep = '', end = '')
                print (a[i])
                exit()

    for i in range(25, -1, -1):
        if i == -1:
            break
        if ord(S[i]) < ord(S[i - 1]):
            continue
        else:
            break
    if i == 0:
        print (-1)
        exit()

    tmp_n = ord('z')
    for j in S[i:]:
        if ord(j) > ord(S[i - 1]):
            tmp_n = min(tmp_n, ord(j))

    print (*S[:i - 1], sep = '', end = '')
    print (chr(tmp_n))
 
    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()

def func(s, remain):
    if not s:
        if remain:
            return min(remain)
        else:
            return -1

    T = func(s[1:], remain - set([s[0]]))
    if T == -1:
        cand = [x for x in remain if x > s[0]]
        if cand:
            return min(cand)
        else:
            return -1
    return s[0] + T


rem = set()
for i in range(26):
    rem.add(chr(ord('a') + i))

print(func(S, rem))

Submission status: Accepted

Solution code:
S = list(input())

a = 'abcdefghijklmnopqrstuvwxyz'
if len(S) != 26:
    for i in range(26):
        if not a[i] in S:
            print (*S, sep = '', end = '')
            print (a[i])
            exit()

for i in range(25, -1, -1):
    if i == -1:
        break
    if ord(S[i]) < ord(S[i - 1]):
        continue
    else:
        break
# print (i)
if i == 0:
    print (-1)
    exit()

tmp_n = ord('z')
for j in S[i:]:
    if ord(j) > ord(S[i - 1]):
        tmp_n = min(tmp_n, ord(j))

print (*S[:i - 1], sep = '', end = '')
print (chr(tmp_n))

Submission status: Accepted

Solution code:
def main():
    s = input().strip()
    if len(s) == 26:
        if s == "zyxwvutsrqponmlkjihgfedcba":
            print(-1)
            return
        s = s[::-1]
        pre = ord(s[0]) - ord("a")
        nums = [pre]
        for i in range(1, len(s)):
            tmp = ord(s[i]) - ord("a")
            if tmp < pre:
                min_ = pre
                for num in nums:
                    if num > tmp:
                        min_ = min(min_, num)
                s = s[i+1:]
                # print(nums, ">", tmp, min_)
                print(s[::-1]+chr(min_+ord("a")))
                return
            nums.append(tmp)
            pre = tmp
    else:
        check = [False] * 26
        for i in range(len(s)):
            check[ord(s[i]) - ord("a")] = True
        for i in range(26):
            if not check[i]:
                print(s+chr(ord("a")+i))
                return

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
*l,=map(ord,input()+'`')
for i in range(len(l)):
	p=l[:~i];s=set(range(l[~i]+1,123))-set(p)
	if s:print(*map(chr,p+[min(s)]),sep="");exit()
print(-1)

Submission status: Accepted

Solution code:
d=list("abcdefghijklmnopqrstuvwxyz")
s=input()
ss=list(s)
unused=list(set(d)^set(ss))
unused.sort()
if len(s)==26:
    cnt=1
    l=d.index(s[-1])
    for i in range(2,27):
        if d.index(s[-i])>l:
            l=d.index(s[-i])
            cnt+=1
        else:
            i=ss[-cnt-1]
            j=1
            while True:
                if d.index(i)>d.index(ss[-j]):
                    j+=1
                else:
                    break
            ans=ss[:-cnt-1]+[ss[-j]]
            print("".join(ans))
            exit()
    print(-1)
else:
    ans=ss+[unused[0]]
    print("".join(ans))

Submission status: Accepted

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

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

alpha = 'abcdefghijklmnopqrstuvwxyz'
s = input()
if s == alpha[::-1]:
    print(-1)
elif len(s) < 26:
    for i in alpha:
        if i not in s:
            print(s+i)
            break
else:
    temp=[]
    for i in range(25):
        temp.append(s[-i-1])
        if s[-i-2]<s[-i-1]:
            break
    for t in temp:
        if s[-i-2]<t:
            print(s[:-i-2]+t)
            break

Submission status: Accepted

Solution code:
#%%
alpha2num = lambda c: ord(c) - ord('a') + 1
num2alpha = lambda c: chr(c+64)
S = list(input())

S = S[::-1]
alpha = 'abcdefghijklmnopqrstuvwxyz'
alpha = list(alpha)

a = 0

if len(S) != 26:
    for i in range(len(alpha)):
        if alpha[i] not in S:
            b = alpha[i]
            break
    ans = ''.join(S)[::-1] + b
else:
    for i in range(1,len(S)):
        if S[i] < S[i-1]:
            a = i
            break
    if a == 0:
        ans = -1
    else:
        for i in range(len(alpha)):
            if alpha[i] not in S[a+1:] and alpha[i] > S[a]:
                c = alpha[i]
                break
        ans = (c + ''.join(S[a+1:]))[::-1]

print(ans)

#%%

Submission status: Accepted

Solution code:
# 2019/08/12

s=input()
if s=='zyxwvutsrqponmlkjihgfedcba':
    print(-1)
    exit()

st=set(s)

if len(s)<26:
    for i in range(97,97+26+1):
        if chr(i) in st:continue
        print(s+chr(i))
        exit()

s=list(s)
res=[s.pop()]

def solve(s):
    for _ in range(len(s)):
        tmp=s.pop()
        if tmp>res[-1]:
            res.append(tmp)
            res.sort()
        else:            
            for e in res:
                if e<tmp:continue
                s.append(e)
                return s

print(''.join(solve(s)))

Submission status: Accepted

Solution code:
S0="zyxwvutsrqponmlkjihgfedcba"
S=input()
N=len(S)
if S==S0:
    print(-1)
elif len(S) == 26:
    for i in reversed(range(N-1)):
        if S[i]<S[i+1]:
            for j in reversed(range(i+1,N)):
                if S[j]>S[i]:
                    print(S[:i]+S[j])
                    exit()
else:
    for c in sorted(S0):
        if c not in S:
            print(S+c)
            exit()
#['a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac', 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

S = input()

alphabets = set(chr(ord('a')+x) for x in range(26))

def F(S,alphabets):
    if len(S) == 0:
        return -1
    T = F(S[1:],alphabets-set([S[0]]))
    if T == -1:
        larger = [x for x in alphabets if x > S[0]]
        if not larger:
            return -1
        return min(larger)
    return S[0] + T

answer = F(S,alphabets)
print(answer)

Submission status: Accepted

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)
def input():
  return sys.stdin.readline()[:-1]

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

S = str(input())

alphabet = [chr(i) for i in range(ord('a'),ord('z')+1)]

if len(S)!=26:
  for i in range(len(S)):
    alphabet.remove(S[i])
  print(S+alphabet[0])
else:
  if S == ''.join(list(reversed(alphabet))):
    print(-1)
  else:
    for i in range(1,len(S))[::-1]:
      if S[i]>S[i-1]:
        break
    temp = 'z'
    for j in range(i,len(S)):
      if S[j]>S[i-1] and temp > S[j]:
        temp = S[j]
    print(S[:i-1]+temp)

Submission status: Accepted

Solution code:
S=list(input())
l=len(S)

available=[]
for i in range(26):
    available.append(chr(i+97))

for i in S:
    available.remove(i)

if l<26:
    S.append(available[0])
else:
    f=0
    for i in range(l):
        start=ord(S[-1])+1
        for i in range(26):
            want=chr(start+i)
            if want in available:
                S.remove(S[-1])
                S.append(want)
                f=1
                break
        if f==1:
            break
        else:
            available.append(S[-1])
            S.remove(S[-1])
if len(S)==0:
    ans='-1'
else:
    ans=''
    for i in S:
        ans+=i
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from copy import *

S = input()
if S == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)
    exit()
atoz = [chr(i) for i in range(97,97+26)]
N = len(S)
if N == 26:
    for i in range(N-1)[::-1]:
        if S[i] < S[i+1]:
            print(S[:i]+min([y for y in S[i+1:] if y > S[i]]))
            break
else:
    for c in atoz:
        if not c in S:
            print(S+c)
            break

Submission status: Accepted

Solution code:
# AGC022A - Diverse Word
def main():
    S = input().rstrip() + "`"  # add "`" to get full S when S[:-1]
    for i in range(len(S)):
        P = S[:~i]  # partial string
        # get possible letters after S[~i]
        R = set(chr(i) for i in range(ord(S[~i]) + 1, 123)) - set(P)
        if R:
            print(P + min(R))
            break
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import string
def solve(s):
    if len(s) < 26: # なにかの文字を末尾に追加できる
        for c in string.ascii_lowercase:
            if not c in s:
                return s + c
    # 繰り上げが存在
    i = len(s) - 2
    while i >= 0:
        for cand in sorted(s[i+1:]):
            if s[i] < cand:
                return s[:i] + cand
        i -= 1
    return -1

assert solve("atcoder") == "atcoderb"
assert solve("abc") == "abcd"
assert solve("zyxwvutsrqponmlkjihgfedcba") == -1
assert solve("abcdefghijklmnopqrstuvwzyx") == "abcdefghijklmnopqrstuvx"
s = input()
print(solve(s))

Submission status: Accepted

Solution code:
S = input()
alpha = "abcdefghijklmnopqrstuvwxyz"

if len(S) != 26:
    for i in alpha:
        if i not in S:
            print(S+i)
            exit()

for i in range(24, -1, -1):
    for j in range(25, i, -1):
        if S[i] < S[j]:
            print(S[:i]+S[j])
            exit()
print(-1)

Submission status: Accepted

Solution code:
s = input()
t = 'abcdefghijklmnopqrstuvwxyz'
if len(s) == len(t):
  for i in range(24,-1,-1):  
    for j in range(25,i,-1):
      if s[j] > s[i]:
        print(s[:i]+s[j])
        exit()
  print(-1)
  exit()
else:
  for i in t:
    if i not in s:
      print(s+i)
      exit()

Submission status: Accepted

Solution code:
S=input()

if S == 'zyxwvutsrqponmlkjihgfedcba':
    ans='-1'
else:
    if len(S)<26:
        for c in [chr(ord('a') + i) for i in range(26)]:
            if c not in S:
                ans = S+c
                break
    else:
        for i in range(25):
            if ord(S[25-i-1]) < ord(S[25-i]):
                for c in sorted(S[25-i:]):
                    if ord(S[24-i]) < ord(c):
                        ans=S[:24-i] + c
                        break
                break

print(ans)

Submission status: Accepted

Solution code:
S = input()

alpha2num = lambda c: ord(c) - ord('a') + 1
num2alpha = lambda c: chr(c+96)

snum = list(map(alpha2num, list(S)))

def next_snum(snum):
    if len(snum) <26:
        for i in range(1,27):
            if not i in snum:
                snum.append(i)
                return snum
    else:
        for i in range(25,0,-1):
#             print("hoge")
            # 後ろから見ていき、左より右が大きいことがあれば、
            if snum[i-1] < snum[i]:
                # i-1番目は消す。i番目以降で、i-1より大きく、もっとも小さい数を足す
                # snum[i]は必ず該当するので、そのようなminnumが1つ以上存在する
                minnum = 27
                for nxt in snum[i:]:
                    if minnum > nxt and nxt > snum[i-1]:
                        minnum = nxt
                        
#                 print("nxt:",nxt)
                snum = snum[:i-1] + [minnum]
#                 print(snum)
                return snum
        # 1つも上記のようなものがなければ、次のSは存在しない
        return -1

result_num = next_snum(snum)

if result_num == -1:
    print(-1)
else:
    print("".join(list(map(num2alpha,result_num))))

Submission status: Accepted

Solution code:
from sys import stdin
import string
import numpy as np

S = (stdin.readline().rstrip())
remain = string.ascii_lowercase

if S == remain[::-1]:
    print(-1)

else:

    for i in S:
        remain = remain.replace(i, "")

    if remain != "":
        ans = S + sorted(remain)[0]
        print(ans)

    else:
        S = np.array(list(S))
        for i in range(25, 0, -1):
            S_left = S[:i]
            S_right = np.sort(S[i:])
            if len(S_right[S_right > S_left[-1]]) != 0:
                ans = list(S[:i-1]) + list(S_right[S_right > S_left[-1]][0])
                ans = "".join(ans)
                print(ans)
                break

Submission status: Accepted

Solution code:
s=input()
lens=len(s)
if lens!=26:
    for i in "abcdefghijklmnopqrstuvwxyz":
        if i not in s:
            print(s+i)
            break
elif s=="zyxwvutsrqponmlkjihgfedcba":
    print(-1)
else:
    temp=[]
    for i in range(25):
        temp.append(s[-i-1])
        if s[-i-2]<s[-i-1]:
            break
    for t in temp:
        if s[-i-2]<t:
            print(s[:-i-2]+t)
            break

Submission status: Accepted

Solution code:
import string

S = input()

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

if len(S) < 26:
    for s in S:
        abc.remove(s)
    add = abc[0]
    print(S + add)
elif S == ''.join(sorted(abc, reverse=True)):
    print(-1)
else:
    N = len(S)
    for i in range(1, N):
        now = S[N-i-1]
        fow = S[N-i:]
        fows = sorted(list(fow))
        for f in fows:
            if now < f:
                now = f
                break
        if now != S[N-i-1]:
            ans = S[:N-i-1] + now
            break
    print(ans)

Submission status: Accepted

Solution code:
s=input()
t="abcdefghijklmnopqrstuvwxyz"
if s==t[::-1]:print(-1);exit()
if len(s)<26:
  for i in t:
    if not i in s:print(s+i);exit()
else:
  for i in range(25):
    if s[-i-2]<s[-1-i]:
      t=s[:-i-2]
      a=sorted(list(s[-2-i:]))
      print(t+a[a.index(s[-2-i])+1]);exit()

Submission status: Accepted

Solution code:
s=input()

ll=["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:
    l=list(s)
    for i in l:
        ll.remove(i)
    ll.sort()
    print(s+ll[0])
else:
    if s=="zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    else:
        l=[]
        for i in range(1,27):
            for j in l:
                if s[-i]<j:
                    print(s[0:26-i]+j)
                    import sys
                    sys.exit()
            l.append(s[-i])
            l.sort()

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, ceil, floor
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
import heapq
INF = float("inf")
sys.setrecursionlimit(10**7)
# 4近傍（右, 下, 左, 上）
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
def inside(y: int, x: int, H: int, W: int) -> bool: return 0 <= y < H and 0 <= x < W
def mi(): return map(int, input().split())
def ii(): return int(input())
###template###

S = input()

end = "abcdefghijklmnopqrstuvwxyz"[::-1]

if S == end:
  print(-1)
  exit()

lastChar = S[-1]
set_used = set(S)

if len(S)<len(end): #付け加える文字が残っている場合
  for i in range(ord('a'), ord('z')+1):
    if not chr(i) in set_used:
      print(S + chr(i))
      exit()
else: #全文字使っている場合、全探索
  prevord = -1
  for i, c in enumerate(S[::-1]): #iは後ろから何文字目か(0-indexed)
    if ord(c)<prevord: #Si, Si+1が昇順だったら
      #Siを、i-1までで一度も使っていない一番若い文字に変える
      ansS_exceptLast = S[0:-i-1]
      for cc in range(ord(c)+1, ord('z')+1):
        if not chr(cc) in ansS_exceptLast:
          print(ansS_exceptLast+chr(cc))
          exit()
    else:
      prevord = ord(c)

Submission status: Accepted

Solution code:
wrd = [chr(i+97) for i in range(26)]
S = input()
ans = ''
for s in S:
    wrd.remove(s)
wrd.sort()
if(S=='zyxwvutsrqponmlkjihgfedcba'):
    print(-1)
elif(len(S)<26):
    print(S+wrd[0])
else:
    chrs = []
    for i in range(len(S)-1,-1,-1):
        for j in chrs:
            if(j>S[i]):
                ans = S[:i]+j
                break
        else:
            chrs.append(S[i])
            chrs.sort()
            continue
        break

    print(ans)

Submission status: Accepted

Solution code:
s=input()
a='abcdefghijklmnopqrstuvwxyz'
r='zyxwvutsrqponmlkjihgfedcba'
if len(s)!=26:
  for i in a:
    if i not in s:
      s=s+i
      break
elif s==r:
  s=-1
else:
  for i in range(25,0,-1):
    if i==1:
      s=chr(ord(s[0])+1)
      break
    if s[i]>s[i-1]:
      l=sorted(s[i:])
      for j in l:
        if j>s[i-1]:
          m=j
          break
      s=s[:i-1]+m
      break
print(s)

Submission status: Accepted

Solution code:
def main():
    S = input()
    if len(S) < 26:
        exists = set()
        for c in S:
            exists.add(c)
        for i in range(26):
            x = chr(ord('a') + i)
            if x not in exists:
                print(S + x)
                return
    seen = []
    for i in range(25, -1, -1):
        last = None
        for x in seen:
            if S[i] < x:
                if last == None or x < last:
                    last = x
        if last:
            print(S[:i] + last)
            return
        seen.append(S[i])
    print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
S = list(input())
S = [ord(x) for x in S]
S_exist = sorted(S)
if len(S_exist) != 26:
    for i in range(len(S_exist)):
        if S_exist[i] != i+97:
            S.append(i+97)
            break
    if len(S_exist) == len(S):
        S.append(max(S_exist)+1)
    print("".join(map(str, [chr(x) for x in S])))
else:
    S.reverse()
    if S == S_exist:
        print(-1)
    else:
        flag = 0
        for i in range(25):
            if S[i] > S[i+1]:
                a = S[i+1]
                for j in sorted(S[:i+2]):
                    if j > a:
                        S = [j] + S[i+2:]
                        flag = 1
                        break
            if flag == 1:
                break
        S.reverse()
        print("".join(map(str, [chr(x) for x in S])))

Submission status: Accepted

Solution code:
S = input()
alpha = 'abcdefghijklmnopqrstuvwxyz'
if S == alpha[::-1]:
    print(-1)
else:
    rest = sorted(list(set(alpha) - set(S)))
    if rest:
        print(S + rest[0])
    else:
        for i in range(len(S)-1, 0, -1):
            if S[i-1] < S[i]:
                break
        rest = sorted([s for s in S[i:] if s > S[i-1]])
        print(S[:i-1] + rest[0])

Submission status: Accepted

Solution code:
s = str(input())
alpha = "abcdefghijklmnopqrstuvwxyz"
if len(s) < 26:
    toappend = ""
    for i in alpha:
        if i not in s:
            toappend = i
            break
    s += toappend
    print(s)
else:
    if s == alpha[::-1]:
        print(-1)
    else:
        s = s[::-1]
        ckd = []
        for i in range(26):
            for j, it in enumerate(ckd):
                if s[i] < it:
                    temp = ckd[j] + s[i+1:]
                    print(temp[::-1])
                    exit()
            ckd.append(s[i])

Submission status: Accepted

Solution code:
S=input()
Sf = S+" "

Flag = True
for i in range(len(S)*2):
  se = set(S)
  p = -1
  for i in range(26):
    if chr(ord('a')+i) not in se and ord('a')+i > ord(Sf[len(S)]):
      p= i
      break
    p = -1
  #print ( S + chr(ord('a')+p) ) 
  if (p == -1):
    if ( len(S)==0 ):
        Flag = False
        break
    S = S[:-1]
  else:
    break
    
if ( Flag ):
  print ( S + chr(ord('a')+p) ) 
else:
  print ( -1 )

Submission status: Accepted

Solution code:
s = input().rstrip()
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
elif len(s) == 26:
    s = s[::-1]
    seen = []
    for i in range(26):
        for j, item in enumerate(seen):
            if s[i] < item:
                ns = seen[j] + s[i+1:]
                print(ns[::-1])
                exit()
        seen.append(s[i])
else:
    alphabets = set(s)
    for item in "abcdefghijklmnopqrstuvwxyz":
        if item not in alphabets:
            print(s + item)
            exit()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
A - Diverse Word
https://atcoder.jp/contests/agc022/tasks/agc022_a

"""
import sys


from string import ascii_lowercase

def solve(S):
    if len(S) < len(ascii_lowercase):
        remaining = sorted(set(ascii_lowercase) - set(S))
        return S + remaining[0]
    for p in range(len(S)-1, -1, -1):
        pre = S[:p]
        ch = chr(ord(S[p]) + 1)
        while 'a' <= ch <= 'z':
            if ch not in pre:
                return pre + ch
            ch = chr(ord(ch) + 1)
    return -1


def main(args):
    S = input()
    ans = solve(S)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
import collections
S = input()
alp = 'abcdefghijklmnopqrstuvwxyz'
dic = collections.defaultdict(int)
ans = -1
if len(S) <= 25:
    for i in S:
        dic[i] += 1
    for i in alp:
        if dic[i] == 0:
            ans = S + i
            break
else:
    dic2 = {}
    dic3 = {}
    lst = []
    tmp = 0
    flag = False
    for i, j in zip(alp, range(1, 27)):
        dic2[i] = j
        dic3[j] = i
    for i in range(1, 27):
        a2 = S[-i]
        idx = dic2[a2]
        if idx < tmp:
            lst.sort()
            for j in lst:
                if j > idx:
                    ans = S[:-i] + dic3[j]
                    flag = True
                    break
        
        else:
            tmp = idx
            lst.append(idx)
        if flag:
            break

print(ans)

Submission status: Accepted

Solution code:
import itertools
import string
n=26
alp=string.ascii_lowercase[0:n]

def nextchar(c):
    if c==alp[n-1]:
        return '0'
    z=alp
    return z[alp.find(c)+1]
    
def nextword(c):
    if c==alp[::-1]:
        return -1
    else:
        while True:
            c=c[:len(c)-1]
            l=nextchar(c[-1])
            while l!='0':
                if l not in c:
                    return c[:len(c)-1]+l
                l=nextchar(l)

s=input()
if len(s)<n:
        for i in alp:
            if i not in s:
                print(s+i)
                break
else:
    print(nextword(s))

Submission status: Accepted

Solution code:
S=input()
final=(''.join([ chr(97+i) for i in range(26)]))[::-1]
if S==final:
	print('-1')
else:
	if len(S)<26:
		for i in range(26):
			if chr(97+i) in S:
				continue
			else:
				print(S+chr(97+i))
				break
	else:
		S_cut = S
		continuate = True
		while continuate:
			S_cut = S_cut[:-1]
			tail = ord(S_cut[-1]) - ord('a')
			for i in range(tail+1, 26):
				if chr(97+i) in S_cut[:-1]:
					continue
				else:
					print(S_cut[:-1]+chr(97+i))
					continuate = False
					break

Submission status: Accepted

Solution code:
s=input()
if len(s)!=26:
    c = sorted(set("abcdefghijklmnopqrstuvwxyz")-set(s))[0]
    print(s+c)
elif s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
else:
    s=list(s)
    m=[s.pop()]
    while 1:
        q=s.pop()
        if max(m)>q:
            c=min(a for a in m if a>q)
            print("".join(s)+c)
            break
        else:
            m.append(q)

Submission status: Accepted

Solution code:
from string import ascii_lowercase
h = {ascii_lowercase[i]:i for i in range(26)}
S = input()
c = set(ascii_lowercase) - set(S)
if len(c) > 0:
    print(S + sorted(c)[0])
else:
    for i in range(len(S)-1, -1, -1):
        j = h[S[i]]
        for k in range(j+1, 26):
            if not ascii_lowercase[k] in S[:i]:
                print(S[:i] + ascii_lowercase[k])
                exit()
    print(-1)

Submission status: Accepted

Solution code:
S = input()

def solve(S):
    if len(S) < 26:
        return S + min(set(chr(ord('a') + i) for i in range(26)) - set(S))
    for i in range(len(S) - 1, 0, -1):
        if S[i - 1] < S[i]:
            return S[:i - 1] + min(s for s in S[i:] if s > S[i - 1])
    return "-1"

print(solve(S))

Submission status: Accepted

Solution code:
s=input()
abc="abcdefghijklmnopqrstuvwxyz"
if len(s)<26:
  print(s+sorted(list(set(abc)-set(s)))[0])
else:
  x=s[-1]
  Tail=[x]
  count,flag=0,0
  for i in range(2,27):
    if s[-i]<x:
      count=i
      flag=1
      break
    else:
      x=s[-i]
      Tail.append(x)
  t="z"
  if count!=0:
    for tt in Tail:
      if tt>s[26-count]:
        t=min(t,tt)  
  print(-1 if flag==0 else s[:-count]+t)

Submission status: Accepted

Solution code:
S = input()

def next_tasai(S):
  if S == 'zyxwvutsrqponmlkjihgfedcba':
    return -1
  
  A = 'abcdefghijklmnopqrstuvwxyz'
  Aset = set([a for a in A])
  Sset = set([s for s in S])
  
  if (Aset-Sset):
    l = min(Aset-Sset)
    answer = S+l
    return answer
  else:
    i=-1
    while True:
      if S[i] < S[i-1]:
        i-=1
      else:
        key = min([s for s in S[i-1:] if s>S[i-1]])
        return S[:i-1] + key
      
print(next_tasai(S))

Submission status: Accepted

Solution code:
check='abcdefghijklmnopqrstuvwxyz'
s=input()
l=len(s)
if l<=25:
  for i in range(25):
    if check[i] not in s:
      print(s+check[i])
      break
else:
  s2=''.join(map(str,sorted(s,reverse=True)))
  if s==s2:
    print(-1)
  else:
    for i in range(25):
      if s[-(i+1)]>s[-(i+2)]:
        tmp1=s[:-(i+2)]
        tmp2=s[-(i+2):]
        break
    base=tmp2[0]
    minc=10**9
    for i in range(1,len(tmp2)):
      tmpv=ord(tmp2[i])-ord(base)
      if tmpv>0 and tmpv<minc:
        minc=tmpv
    print(tmp1+chr(ord(base)+minc))

Submission status: Accepted

Solution code:
s = input()

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


if len(s)!=26:
    for i in range(26):
        if chr(97+i) not in s:
            print(s+chr(97+i))
            exit()
else:
    for i in range(25):
        if s[24-i]<s[25-i]:
            m = s[25-i]
            for x in s[25-i:]:
                if x > s[24-i]:
                    m = min(m, x)
            print(s[:24-i]+m)
            exit()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()+"`"
for j in reversed(range(len(s))):
    a=set(map(chr,range(ord(s[j])+1,123)))-set(s[:j])
    if len(a)>0:
        print(s[:j]+min(a))
        exit()
print(-1)

Submission status: Accepted

Solution code:
s = input()+"`"

for j in reversed(range(len(s))):
    sets=set(s[:j])
    for i in range(ord(s[j])+1,123):
        if chr(i) not in sets:
            print(s[:j] + chr(i))
            exit()
print(-1)

Submission status: Accepted

Solution code:
import sys

S = input()
alphabets = 'abcdefghijklmnopqrstuvwxyz'
seen = set(list(S))

if len(S) < 26:
    for c in alphabets:
        if c not in seen:
            print(S + c)
            sys.exit()

for i in range(len(S)):
    t = S[-1-i]
    if t != 'z':
        for t_dash in alphabets[alphabets.find(t)+1:]:
            if t_dash not in seen:
                print(S[:-1-i] + t_dash)
                sys.exit()
    seen.remove(t)

print('-1')

Submission status: Accepted

Solution code:
a = set(["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 len(s)<26:
    b = list(a-set(s))
    b.sort()
    print(s+b[0])
else:
    for i in range(2,27):
        if s[-i] < s[-i+1]:
            break
        if i == 26:
            print(-1)
            exit()
    for j in sorted(s[-i+1:]):
        if j > s[-i]:break
    print(s[:-i]+j)

Submission status: Accepted

Solution code:
import numpy as np
alp = [chr(v) for v in range(ord("a"), ord("z") + 1)]
inp = input()

if inp[::-1] == "".join(alp):
    print(-1)
    exit()

if len(inp) == len(alp):
    prev = inp[0]
    indices = [0]
    for index, char in enumerate(inp[1:]):
        if prev < char:
            indices.append(index)
        prev = char
    # diff = [0] * (len(indices) - 1)
    # for i, (v1, v2) in enumerate(zip(indices[1:], indices[:-1])):
    #     diff[i] = v1 - v2
    # maxv = float("-inf")
    # maxv_index = 0
    # for i, d in enumerate(diff):
    #     if maxv <= d:
    #         maxv = d
    #         maxv_index = i
    #
    # index = indices[maxv_index + 1]
    index = indices[-1]
    targets = inp[index + 1:]
    for v in sorted(targets):
        if inp[index] < v:
            break
    print(inp[:index] + v)

else:
    print(inp + min(set(alp) - set(list(inp))))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

N = input()
p = list("abcdefghijklmnopqrstuvwxyz")

if len(N) != 26:
    for i in N:
        p.pop(p.index(i))
    if p == []:
        print(-1)
        exit()
    print(N+p[0])
else:
    tmp = 0
    a = list("zyxwvutsrqponmlkjihgfedcba")
    if a == list(N):
        print("-1")
        exit()
    for i in range(24,-1,-1):
        for c in p:
            if c not in N[:i] and c > N[i]:
                print(N[:i]+c)
                exit()