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 = list(input())
L = len(S)

if L != 26:
  # まだ使ってないもので、最大ものもを最後につける
  USED = [False] * 26
  for s in S:
    USED[ord(s) - 97] = True
  
  for i in range(26):
    if not USED[i]:
      S.append(chr(97+i))
      break
  
  print("".join(S))
else:
  # 26文字ある場合
  prev = -1
  k = -1
  USED = []
  for i in range(26)[::-1]:
    d = ord(S[i]) - 97
    if prev < d:
      prev = d
      USED.append(S[i])
    else:
      k = i
      break
  
  if k == -1:
    print(-1)
  else:  
    nxt = min([s for s in USED if s > S[k]])
    S = S[:k] + [nxt]
    print("".join(S))

Submission status: Accepted

Solution code:
s = input()
if s == "zyxwvutsrqponmlkjihgfedcba":
  print(-1)
elif len(s) == 26:
  l = []
  for i in range(26)[::-1]:
    ds = s[i]
    l.append(ds)
    if ds != max(l):
      l.sort()
      for j in l:
        if ds < j:
          break
      print(s[:i]+j)
      break
else:
  for i in list("abcdefghijklmnopqrstuvwxyz"):
    if i in s:
      continue
    else:
      print(s+i)
      break

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:
# https://atcoder.jp/contests/agc022/tasks/agc022_a

import sys
s = input()
A = [chr(ord("a") + i) for i in range(26)]
if len(s) < 26:
  for a in A:
    if a not in s:
      print(s + a)
      sys.exit()
else:
  for p in range(26)[::-1]:
    for a in A[A.index(s[p])+1:]:
      if a not in s[:p]:
        print(s[:p] + a)
        sys.exit()
print(-1)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

S = input()

alphas = [chr(ord('a') + i) for i in range(26)]

if len(S) < 26:
    remain = set(alphas) - set(S)
    remain = sorted(remain)
    print(S + remain[0])
else:
    pre = S[-1]
    i = 2
    while i < len(S):
        if pre < S[len(S) - i]:
            pre = S[len(S) - i]
            i += 1
        else:
            break
    if i == 26 and S[0] == 'z':
        print(-1)
        exit()
    front = S[:-i]
    back = sorted(S[-i:])
    to_be_changed = S[-i]
    for c in back:
        if c > to_be_changed:
            print(front + c)
            break

Submission status: Accepted

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

if n!=26:
  for i in [chr(ord('a') + i) for i in range(26)]:
    if not i in s:
      tmp=i
      break
  s.append(tmp)
  print("".join(s))

else:
  if "".join(s)=="zyxwvutsrqponmlkjihgfedcba":
    print(-1)

  else:
    for j in range(n)[::-1]:
      for k in range(1,122-ord(s[j])+1):
        tmp = chr(ord(s[j])+k)
        if tmp not in s[:j]:
          s[j]=tmp
          del s[j+1:]
          print("".join(s))
          exit()

Submission status: Accepted

Solution code:
s=input()
alp='abcdefghijklmnopqrstuvwxyz'

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

d={}
e={}
for i in range(len(alp)):
    d[alp[i]]=i
    e[i]=alp[i]

n=len(s)
if n!=26:
    ans=[]
    for i in range(n):
        ans.append(d[s[i]])

    for j in range(26):
        if j not in ans:
            ans.append(j)
            break

    st=''
    for k in ans:
        st+=e[k]
else:
    arr=[]

    dp=[]
    for i in range(n):
        dp.append(d[s[i]])
    
    while True:
        v=dp.pop()

        tmp=[j for j in arr if j>v]
        if len(tmp)!=0:
            dp.append(min(tmp))
            break
        
        arr.append(v)
        
    st=''
    for k in dp:
        st+=e[k]



print(st)

Submission status: Accepted

Solution code:
def next_permutation(case):
    for index in range(1, len(case)):
        Px_index = len(case) - 1 - index
        # Start travelling from the end of the Data Structure
        Px = case[-index - 1]
        Px_1 = case[-index]

        # Search for a pair where latter the is greater than prior
        if Px < Px_1:
            suffix = case[-index:]
            pivot = Px
            minimum_greater_than_pivot_suffix_index = -1
            suffix_index = 0

            # Find the index inside the suffix where ::: [minimum value is greater than the pivot]
            for Py in suffix:
                if pivot < Py:
                    if minimum_greater_than_pivot_suffix_index == -1 or \
                            suffix[minimum_greater_than_pivot_suffix_index] >= Py:
                        minimum_greater_than_pivot_suffix_index = suffix_index
                suffix_index += 1
            # index in the main array
            minimum_greater_than_pivot_index = minimum_greater_than_pivot_suffix_index + Px_index + 1

            # SWAP
            temp = case[minimum_greater_than_pivot_index]
            case[minimum_greater_than_pivot_index] = case[Px_index]
            case[Px_index] = temp

            # Sort suffix
            new_suffix = case[Px_index + 1:]
            new_suffix.sort()

            # Build final Version
            new_prefix = case[:Px_index + 1]
            next_permutation = new_prefix + new_suffix
            return next_permutation
        elif index == (len(case) - 1):
            # This means that this is at the highest possible lexicographic order
            return False


s = input()
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
elif len(s) != 26:
    used = [False] * 26
    for i in range(len(s)):
        used[ord(s[i]) - ord("a")] = True
    for i in range(26):
        if used[i] is False:
            s += chr(ord("a") + i)
            print(s)
            break
else:
    dat = []
    for i in range(len(s)):
        dat.append(ord(s[i]) - ord("a"))
    #print(dat)
    #print(next_permutation(dat))
    dat = next_permutation(dat)
    res = ""
    t = "".join(list(map(lambda x: chr(ord("a") + x), dat)))
    for i in range(26):
        print(t[i], end="")
        if s[i] != t[i]:
            break
    print("")

Submission status: Accepted

Solution code:
S=input()
if len(S)<26:
    for char in range(ord("a"),ord("z")):
        if chr(char) not in S:
            break
    print(S+chr(char))
else:
    stack=list(S[-1])
    for s in S[len(S)-2::-1]:
        if s>stack[-1]:
            stack.append(s)
        else:
            break
    if len(stack)==26:
        print(-1)
    else:
        print(S[0:len(S)-len(stack)-1]+min(char for char in stack if char>S[-len(stack)-1]))

Submission status: Accepted

Solution code:
S=input()
if len(S)<26:
    for char in range(ord("a"),ord("z")):
        if chr(char) not in S:
            break
    print(S+chr(char))
else:
    stack=list(S[-1])
    for s in S[len(S)-2::-1]:
        if s>stack[-1]:
            stack.append(s)
        else:
            break
    if len(stack)==26:
        print(-1)
    else:
        print(S[:-len(stack)-1]+min(s for s in stack if s>S[-len(stack)-1]))

Submission status: Accepted

Solution code:
s = input()
dic = {chr(c): 0 for c in range(ord('a'), ord('z') + 1)}
# -1のケース
if s == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)
    exit()

# 出てきた文字をチェック
for c in s:
    dic[c] += 1

# 26文字未満の場合は最後に使っていない最小文字付け足す
if len(s) != 26:
    for k, v in dic.items():
        if v == 0:
            print(s + k)
            exit()
# 全種使っている
else:
    # どこからラストまで降順に並んでいるのか
    # ....stuvw zyx
    # ↑ならzyxが降順になっている
    left = 0
    for i in range(len(s) - 1):
        if s[i] > s[i + 1]:
            pass
        else:
            left = i + 1

    # 降順の部分を分離
    s_down = s[left:]
    check = s[left - 1]
    s_down = reversed(s_down)

    # s_down直前の文字より大きいかつs_down内の最小文字で直前の文字を置き換える
    # ....stuvw zyx
    # なら，wをzyxの中の最小かつwより大きいxで置き換え
    for c in s_down:
        if check < c:
            print(s[:left-1] + c)
            exit()

Submission status: Accepted

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

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

lis =[]
T = S
if len(S)<26:
    Sset = set(S)
    for s in slist:
        if s not in Sset:
            print(S+s)
            exit()
else:
    while len(S)>0:
        lis.append(S[-1])
        lis.sort()
        S = S[:-1]
        for s in lis:
            if S + s > T:
                print(S + s)
                exit()

Submission status: Accepted

Solution code:
string = input()
if len(string) < 26:
  for i in range(97, 124):
    if chr(i) not in string:
      break
  print(string + chr(i))
else:
  val = [string[-1]]
  for i in string[-2::-1]:
    if i > val[-1]:
      val.append(i)
    else:
      break
  if len(val) == 26:
    print(-1)
  else:
    print(string[:-len(val)-1] + min(i for i in val if i > string[-len(val)-1]))

Submission status: Accepted

Solution code:
S = input()

alpha = 'abcdefghijklmnopqrstuvwxyz'
# len(S)が26未満の場合
if len(S) < 26:
    for char in alpha:
        # Sに入っていない文字の中で最小のものを末尾に足す
        if char not in S:
            print(S + char)
            exit()

# len(S)が26の場合
else:
    arr = [S[-1]]

    for i in range(1, 26):
        l = 25 - i
        if max(arr) > S[l]:
            chars = []

            for c in arr:
                # 下のifがよくわかってない
                # bcdefghijklmnopqrstuvwx | zya　みたいな時のため？
                # ifがないと~~~vwa とか吐いて前に戻ってしまうっぽい
                # 時間内に思いつく気が全くしない
                if c > S[l]:
                    chars.append(c)
            char = min(chars)
            # print(chars)

            # for c in arr:
            #     chars.append(c)
            # char = min(chars)

            print(S[:l] + char)
            exit()
        else:  # max(sr)>S[l]　の場合
            arr.append(S[l])

    print(-1)

Submission status: Accepted

Solution code:
S = input()

alpha = 'abcdefghijklmnopqrstuvwxyz'
# len(S)が26未満の場合
if len(S) < 26:
    for char in alpha:
        # Sに入っていない文字の中で最小のものを末尾に足す
        if char not in S:
            print(S + char)
            exit()

# len(S)が26の場合
else:
    arr = [S[-1]]

    for i in range(1, 26):
        l = 25 - i
        if max(arr) > S[l]:
            chars = []

            for c in arr:
                if c > S[l]:
                    chars.append(c)
            char = min(chars)

            # for c in arr:
            #     chars.append(c)
            # char = min(chars)

            print(S[:l] + char)
            exit()
        else:  # max(sr)>S[l]　の場合
            arr.append(S[l])

    print(-1)

Submission status: Accepted

Solution code:
string = input()
if len(string) < 26:
  for i in range(97, 124):
    if chr(i) not in string:
      break
  print(string + chr(i))
else:
  val = [string[-1]]
  for i in string[-2::-1]:
    if i > val[-1]:
      val.append(i)
    else:
      break
  if len(val) == 26:
    print(-1)
  else:
    print(string[:-len(val)-1] + min(i for i in val if i > string[-len(val)-1]))

Submission status: Accepted

Solution code:
s = input()
alpha = 'abcdefghijklmnopqrstuvwxyz'
if len(s) < 26:
  for c in alpha:
    if c not in s:
      print(s + c)
      break
else:
  sr = {s[-1]}
  for i in range(1, len(s)):
    leng = len(s) - i - 1
    if max(sr) > s[leng]:
      print(s[:leng] + min(c for c in sr if c > s[leng]))
      break
    sr.add(s[leng])
  else:
       print(-1)

Submission status: Accepted

Solution code:
s = input()
text = 'abcdefghijklmnopqrstuvwxyz'
if len(s) < 26:
  for c in text:
    if c not in s:
      print(s + c)
      break
else:
  cand = {s[-1]}
  for i in range(1, len(s)):
    j = len(s) - i - 1
    if max(cand) > s[j]:
      print(s[:j] + min(c for c in cand if c > s[j]))
      break
    cand.add(s[j])
  else:
    print(-1)

Submission status: Accepted

Solution code:
from string import ascii_lowercase
alphabets = ascii_lowercase
s = input()
if len(s) < len(alphabets):
    for c in alphabets:
        if c not in s:
            print(s + c)
            exit()
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()

# 14253 next 143,  54213 next 5423, 35421 next 4, 43521 next 45
# 右端からみてi-1, iを比較して減少(S[i]>S[i-1])してたらi-1を基準に切り替える
# 切り替えるのは勘だけどi-1より右側でi-1より大きい最小のやつ？
for i in range(len(s) - 1, 0, -1):
    if s[i] > s[i - 1]:
        t = "死"
        for j in range(i, len(s)):
            if s[i - 1] < s[j]:
                t = s[j] if s[j] < t else t
        print(s[:i - 1] + t)
        exit()

Submission status: Accepted

Solution code:
from string import ascii_lowercase
alphabets = ascii_lowercase
s = input()
if len(s) < len(alphabets):
    for c in alphabets:
        if c not in s:
            print(s + c)
            exit()
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()

# 14253 next 143,  54213 next 5423, 35421 next 4, 43521 next 45
# 右端からみてi-1, iを比較して減少(S[i]>S[i-1])してたらi-1を基準に切り替える
# 切り替えるのは勘だけどi-1より右側でi-1より大きい最小のやつ？
for i in range(len(s) - 1, 0, -1):
    if s[i] > s[i - 1]:
        t = []
        for j in range(i, len(s)):
            if s[i - 1] < s[j]:
                t.append(s[j])
        x = min(t)
        print(s[:i - 1] + x)
        exit()

Submission status: Accepted

Solution code:
S = input()

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

def F_short(S):
    se = alphabet -set(S)
    x = min(se)
    return S + x
    
def F_long(S):
    if S == ''.join(sorted(alphabet, reverse=True)):
        return '-1'
        
    cand = []
    S = list(S)
    while True:
        x = S[-1]
        if not cand or (x > max(cand)):
            cand.append(S.pop())
            continue
        y = min(ch for ch in cand if ch > x)
        return ''.join(S[:-1]) + y
        
L = len(S)
answer = F_short(S) if L < 26 else F_long(S)
print(answer)

Submission status: Accepted

Solution code:
s = input()
if len(s) != 26:
    x = sorted(set(map(chr, range(97, 123)))-set(s))
    print(s+x[0])
else:
    num = list(map(lambda x: ord(x)-ord('a'), s))
    for i in reversed(range(25)):
        L, R = i, i+1
        if num[L] < num[R]:
            tmp = 26
            for r in num[R:]:
                if num[L] < r:
                    tmp = min(tmp, r)
            ans = num[:L]+[tmp]
            print(''.join(map(lambda x: chr(x+ord('a')), ans)))
            break
    else:
        print(-1)

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 i not in S:
      print(S+i)
      exit()
k = 25
while S[k-1] > S[k]:
  k -= 1
X = S[k-1]
Y = list(S[k-1:])
Y.sort()
print(S[:k-1] + Y[Y.index(X) + 1])

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc022/tasks/agc022_a
# いままで登場してない文字で最小のものをappendすれば良い
# ただし26文字すべて出現している場合には考える必要あり
# つまり後ろからi文字目はそれ以降に出現した文字を使って一つだけ大きくできれば良い

S = input()
abc = list(reversed('zyxwvutsrqponmlkjihgfedcba'))

if S == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)
elif len(S) < 26:
    for s in S:
        abc.remove(s)
    print(S + abc[0])
else:
    canuse = set()
    for i in range(25, -1, -1):
        canuse.add(S[i])
        add = None
        for can in sorted(canuse):
            if can > S[i]:
                add = can
                break
        if add != None:
            print(S[:i] + add)
            exit()

Submission status: Accepted

Solution code:
s = input()
if len(s) < 26:
  for i in range(97, 124):
    if chr(i) not in s:
      break
  print(s + chr(i))
else:
  prep = [s[-1]]
  for i in s[-2::-1]:
    if i > prep[-1]:
      prep.append(i)
    else:
      break
  if len(prep) == 26:
    print(-1)
  else:
    print(s[:-len(prep)-1] + min(i for i in prep if i > s[-len(prep)-1]))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def next_vary(S):
    if len(S) < 26:
        alpha = [0] * 26
        for s in S:
            alpha[ord(s) - 97] += 1
        add = None
        for i in range(26):
            if alpha[i] == 0:
                add = chr(i + 97)
                break
        S.append(add)
        return ''.join(S)
    
    else:
        before = set(S)
        flag = False
        for i in range(25,-1,-1):
            s = S[i]
            if s == 'z':
                before.discard('z')
                S.pop()
            else:
                asc = ord(s)
                for j in range(1,25):
                    if asc + j <= 122 and chr(asc + j) not in before:
                        S[i] = chr(asc + j)
                        flag = True
                        break
                if flag:
                    break
                before.discard(s)
                S.pop()
        return ''.join(S)

def main():
    S = input()
    if S == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
        return
    
    ans = next_vary(list(S))
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()

if len(S) < 26:
    for i in range(26):
        if chr(i+97) not in S:
            ans = S + chr(i+97)
            break
elif S == "zyxwvutsrqponmlkjihgfedcba":
    ans = -1
else:
    ans = ""
    L = [S[-1]]
    for i in range(24, -1, -1):
        for l in L:
            if S[i] < l:
                for j in range(i):
                    ans += S[j]
                ans += l
                break
        if ans:
            break
        L.append(S[i])
        L.sort()
print(ans)

Submission status: Accepted

Solution code:
A = 'abcdefghijklmnopqrstuvwxyz'
S = input();
if len(S)<26:
    print(S+sorted(set(A)-set(S))[0])
elif S==A[::-1]:
    print(-1); exit()
else:
    _S = S; ans = []
    while len(S)>0:
        ans.append(S[-1]); S = S[:-1]
        ans.sort()
        for a in ans:
            if S[:-1] + a > _S:
                print(S[:-1] + a); exit()

Submission status: Accepted

Solution code:
S = input()
se = set()
for s in S:
    se.add(s)
if len(S) < 26:
    for i in range(26):
        s = chr(ord('a')+i)
        if not s in se:
            print(S+s)
            exit()
else:
    while len(S) > 1:
        se.remove(S[-1])
        S = S[:-1]
        for i in range(ord(S[-1]), ord('z')+1):
            s = chr(i)
            if not s in se:
                print(S[:-1]+s)
                exit()
print(-1)

Submission status: Accepted

Solution code:
def main():
    S = input()
    if S == "zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    elif len(S) != 26:
        for i in range(26):
            a = chr(ord('a') + i)
            if a not in S:
                print(S + a)
                return
    else:
        while len(S) > 1:
            S = S[:-1]
            last = S[-1]
            while ord(last) < ord('z'):
                last = chr(ord(last) + 1)
                if last not in S:
                    print(S[:-1] + last)
                    return
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()
is_there = [False for i in range(26)]


for c in s:
    is_there[ord(c)-97] = True

if len(s) == 26:
    flag = True
    buf = []
    rep = None
    for i in range(25):
        buf.append(s[-i-1])
        for b in buf:
            if ord(b) > ord(s[-i-2]):
                rep = -i-2
                flag =False
                break
        if not flag:
            break


    if flag:
        print(-1)
    else:
        tp = s[:rep]
        tails = list(s[rep:])
        tails.sort()
        # print(rep)
        for t in tails:
            if ord(t) > ord(s[rep]):
                print(tp+t)
                break
else:
    for i in range(26):
        if not is_there[i]:
            print(s+chr(i+97))
            break

Submission status: Accepted

Solution code:
S=list(input())
L=[ord(s) for s in S]+[96]
for i in range(len(L)):
    l=L[-1]
    for j in range(l+1,123):
        if j not in L:
            S=S+[chr(j)]
            print(*S,sep="")
            exit()
    else:
        L.pop(-1)
        if S:
            S.pop(-1)
else:
    print(-1)

Submission status: Accepted

Solution code:
S = input()

# 1 <= |S| <= 26
# lowercase

import sys
import copy

def next_permutation(a):
    for i in reversed(range(len(a) - 1)):
        if a[i] < a[i + 1]:
            break
    else:
        return False

    j = next(j for j in reversed(range(i + 1, len(a))) if a[i] < a[j])
    a[i], a[j] = a[j], a[i]
    a[i + 1:] = reversed(a[i + 1:])
    return True

if len(S) == 26:
    sl = list(S)
    if next_permutation(sl):
        np = "".join(sl)
        for b in range(0, 26):
            if np[b] != S[b]:
                print(np[:b+1])
                exit()

    else:
        print(-1)
        exit()
else:
    hist = set(S)
    for c in range(0, 27):
        cand = chr(c+ord('a'))
        if cand not in hist:
            print(S+cand)
            sys.exit()

Submission status: Accepted

Solution code:
a = list(input())
ar = list('abcdefghijklmnopqrstuvwxyz')
if len(a) < 26:
    for r in ar:
        if r not in a:
            print("".join(a) + r)
            exit()
else:
    for i in range(25,0,-1):
        n = ar.index(a[i-1]) 
        b = [ar.index(a[j]) for j in range(i,26)]
        br = []
        for r in b:
            if r > n:
                br.append(r)
        if len(br) > 0:
            print("".join(a[0:i-1]) + ar[min(br)])
            exit()
print(-1)

Submission status: Accepted

Solution code:
s = input()

abclist = ['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']
abcstr = ''.join(abclist)
if s == abcstr[::-1]:
    print(-1)
    exit()
if len(s) != 26:
    for a in abclist:
        if a not in s:
            print(s+a)
            exit()

else:
    i = 25
    while s[i-1] > s[i]:
        i -= 1
        #print(s[i-1], s[i])
    #print(s[i-1], s[i])
    tt = s[i-1]
    ss = list(s[i-1:])
    ss.sort()
    print(s[:i-1]+ss[ss.index(tt)+1])

Submission status: Accepted

Solution code:
#11208467
t="abcdefghijklmnopqrstuvwxyz"
s=input()
if s==t[::-1]:print(-1);exit()
if len(s)!=26:
  for i in t:
    if i not in s:print(s+i);exit()
i=25
while s[i-1]>s[i]:i-=1
tt=s[i-1]
ss=list(s[i-1:])
ss.sort()
print(s[:i-1]+ss[ss.index(tt)+1])

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

def main():
    al = set(list('abcdefghijklmnopqrstuvwxyz'))
    S = input()
    if S == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
    elif len(S)==26:
        for i in range(len(S)-1,-1,-1):
            for x in sorted(list(S[i:])):
                if x > S[i-1]:
                    print(S[:i-1]+x)
                    exit()

    else:
        for i in S:
            al-=set(i)
        al = sorted(list(al))
        print(S+al[0])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

S = input()
def aaa(S):

    Alphabet = "abcdefghijklmnopqrstuvwxyz"

    if len(S) == 26:
        j = 0
        for i in reversed(range(26)):
            while S[i] != Alphabet[j]:
                j = j + 1
                if j == 26:
                    k = 0
                    while S[i] != Alphabet[k]:
                        k += 1
                    while not Alphabet[k] in S[i+1:]:
                        k += 1
                    return S[:i] + Alphabet[k]                
        return -1

    else:
        for i in range(len(Alphabet)):
            j = 0
            while Alphabet[i] != S[j]:
                j += 1
                if j == len(S):
                    return S + Alphabet[i]

print(aaa(S))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

S = input()

A = set(S)

for x in ascii_lowercase:
	if not x in A:
		print(S+x)
		break
else:
	for i in range(len(S)-2, -1, -1):
		if S[i] < S[i+1]:
			for char in sorted(S[i+1:]):
				if S[i] < char:
					print(S[:i]+char)
					break
			else:
				continue
			break
	else:
		print(-1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

S = input()

A = set(S)

for x in ascii_lowercase:
	if not x in A:
		print(S+x)
		break
else:
	if S == ascii_lowercase[::-1]:
		print(-1)
	else:
		for i in range(len(S)-2, -1, -1):
			if S[i] < S[i+1]:
				for char in sorted(S[i+1:]):
					if S[i] < char:
						print(S[:i]+char)
						exit()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

S = input()

A = set(S)

for x in ascii_lowercase:
	if not x in A:
		print(S+x)
		break
else:
	if S == ascii_lowercase[::-1]:
		print(-1)
	else:
		S = S[::-1]
		for i in range(len(S)-1):
			if S[i+1] < S[i]:
				for char in sorted(S[:i+1]):
					if char > S[i+1]:
						print(S[::-1][:-i-2]+char)
						exit()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

S = input()

A = set(S)

for x in ascii_lowercase:
	if not x in A:
		print(S+x)
		break
else:
	B = [S[-1]]
	for i in range(len(S)-2, -1, -1):
		for X in B:
			if S[i] < X:
				print(S[:i]+X)
				exit()
		else:
			insort(B, S[i])
	else:
		print(-1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

S = input()

A = set(S)

for x in ascii_lowercase:
	if not x in A:
		print(S+x)
		break
else:
	B = [S[-1]]
	for i in range(len(S)-2, -1, -1):
		if bisect(B, S[i]) == len(B):
			insort(B, S[i])
		else:
			print(S[:i]+B[bisect(B, S[i])])
			break
	else:
		print(-1)