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:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    s = S()
    if len(s) < 26:
        for c in string.ascii_lowercase:
            if c not in s:
                return s + c
    if s == ''.join([c for c in string.ascii_lowercase][::-1]):
        return -1
    for i in range(25,-1,-1):
        c = s[i]
        if max([_ for _ in s[i:]]) == c:
            continue
        t = [_ for _ in s[i:]]
        t.sort()
        ci = t.index(c)
        return s[:i] + t[ci+1]


print(main())

Submission status: Accepted

Solution code:
s = list(input())
t = [a for a in "abcdefghijklmnopqrstuvwxyz"]
if "".join(s) == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
else:
    if len(s) < 26:
        for i in t:
            if i not in s:
                s += i
                break
        print("".join(s))
    else:
        i = 25
        p = s[i]
        while s[i - 1] > s[i] and i > 0:
            i -= 1
        q = ""
        for k in sorted(set(t) - set(s[:i])):
            if k > s[i - 1]:
                q = k
                break
        print("".join(s[:i - 1]) + q)

Submission status: Accepted

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

alp = 'abcdefghijklmnopqrstuvwxyz'
S = input()
if S == alp[::-1]:
    print(-1)
else:
    if len(S) == len(alp):
        s = []
        for i in range(1, len(S))[::-1]:
            s += [S[i]]
            r = [x for x in s if x > S[i-1]]
            if r:
                print(S[:i-1] + sorted(r)[0])
                break
    else:
        for i in S : alp = alp.replace(i, '')
        print(S+alp[0])

Submission status: Accepted

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

alp = 'abcdefghijklmnopqrstuvwxyz'
S = input()
if S == alp[::-1]:
    print(-1)
else:
    if len(S) == len(alp):
        l = list(S)
        s = []
        for i in range(1, len(S))[::-1]:
            s += [l[i]]
            r = sorted(x for x in s if x > l[i-1])
            if r:
                l = l[:i-1] + [r[0]]
                break
        print(''.join(l))
    else:
        for i in S : alp = alp.replace(i, '')
        print(S+alp[0])

Submission status: Accepted

Solution code:


def main():
    temp=input()
    t1=""
    t2=""
    if temp=="zyxwvutsrqponmlkjihgfedcba":
        print(-1)
        exit()
    elif len(temp)==26:
        temp=list(temp)
        p=0
        for i in range(25):
            if temp[25-i]>temp[25-i-1]:
                p=25-i-1
                # print(p)
                # print(temp[p:])
                q=[k for k in temp[p:] if k>temp[p]] 
                print("".join(temp[:p])+min(q))
                exit()       
    else:
        alps=[chr(ord('a') + i) for i in range(26)]
        for w in list(temp):
            alps.remove(w)
        temp=temp+alps[0]
        print(temp)
        exit()       

    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect

# input
S = input()
# S = "abcdefghijklmnopqrstuvwzyx"
# S = "atcoder"
# S = "qpwoeirutyalskdjfhgzmxnvcb"

s = list(S)
a = []
for i in range(len(s)):
    a.append(ord(s[i]))

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


# function
def func(s_):
    ss_ = []
    for i in range(len(s_)):
        ss_.append(chr(s_[i]))
    ss_ = ''.join(ss_)
    return ss_


# solve
if (len(s) < 26):
    for i in range(len(s)):
        b.remove(a[i])
    a.append(min(b))
    print(func(a))

if (len(s) == 26):
    for i in reversed(range(len(s))):
        if (a[i] < a[i-1]):
            if (i == 1):
                print(-1)
                break
            else:
                continue
        else:
            c = a[0:i]
            d = a[i:len(a)]
            d = sorted(d)
            # a[i-1]よりも大きくて最も小さいものを探す
            num = c.pop()
            ind = bisect.bisect_left(d, num)
            c.append(d[ind])
            print(func(c))
            break

Submission status: Accepted

Solution code:
import sys

N = input()
a = []
c = ['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']
l = list(N)
if N =='zyxwvutsrqponmlkjihgfedcba':
  print(-1)
elif len(N) != 26:
  for i in range(len(N)):
    c.remove(l[i])
  N = N[0: i+1] + c.pop(0)
  print(N)
else:
  for i in range(len(N)-1,0,-1):
    a.append(l[i])
    if ord(l[i]) > ord(l[i-1]):
      for j in range(len(a)):
        if l[i-1] < a[j]:
          print(N[0:i-1]+a[j])
          sys.exit()

Submission status: Accepted

Solution code:
import sys
 
 
alph="abcdefghijklmnopqrstuvwxyz"
allis=list(alph)
S=input()
if(S=="zyxwvutsrqponmlkjihgfedcba"):
    print(-1)
    sys.exit()
 
for i in alph:
    if(i not in S):
        print(S+i)
        sys.exit()
        
l=-1
for i in range(len(S)-1)[::-1]:
    if(ord(S[i])<ord(S[i+1])):
        l=i
        break
        
x=sorted(S[i+1:])
for i in x:
    if(i>S[l]):
        print(S[:l]+i)
        sys.exit()

Submission status: Accepted

Solution code:
import sys

N = input()
a = []
b = ['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']
c = ['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']
l = list(N)
if N =='zyxwvutsrqponmlkjihgfedcba':
  print(-1)
elif len(N) != 26:
  for i in range(len(N)):
    c.remove(l[i])
  N = N[0: i+1] + c.pop(0)
  print(N)
else:
  for i in range(len(N)-1,0,-1):
    a.append(l[i])
    if ord(l[i]) > ord(l[i-1]):
      for j in range(len(a)):
        if l[i-1] < a[j]:
          print(N[0:i-1]+a[j])
          sys.exit()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import itertools

ALPHA = sorted([s for s in 'zyxwvutsrqponmlkjihgfedcba'])


def main():
    S = input().strip()

    if 'zyxwvutsrqponmlkjihgfedcba' == S:
        return '-1'

    if len(set(ALPHA) - set([s for s in S])) != 0:
        return S + sorted(set(ALPHA) - set([s for s in S]))[0]

    for i in range(len(S) - 1, 0, -1):
        if S[i - 1] > S[i]:
            pass
        else:
            break

    for a in sorted(set(ALPHA) - set(S[:i])):
        if a > S[i - 1]:
            return S[:i - 1] + a


if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Accepted

Solution code:
import sys


alph="abcdefghijklmnopqrstuvwxyz"
allis=list(alph)
S=input()
if(S=="zyxwvutsrqponmlkjihgfedcba"):
    print(-1)
    sys.exit()

"""
if(S=="abcdefghijklmnopqrstuvwxyz"):
    print("b")
    sys.exit()
"""
for i in alph:
    if(i not in S):
        print(S+i)
        sys.exit()
        
"""
outp=""
for i in range(len(S)):
    if(S[i]==alph[i]):
        outp+=S[i]
    else:
        outp=outp[:-1]
        outp=outp+alph[i]
        break
"""
l=-1
for i in range(len(S)-1)[::-1]:
    if(ord(S[i])<ord(S[i+1])):
        l=i
        break
        
x=sorted(S[i+1:])
for i in x:
    if(i>S[l]):
        print(S[:l]+i)
        sys.exit()
print("b")

Submission status: Accepted

Solution code:
#p = lambda  x: print(x, end=", ")
p = lambda  x: x

s = input()		# 文字列の入力  abcdefg...


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


from collections import defaultdict
d = defaultdict(int)

S = "abcdefghijklmnopqrstuvwxyz"
for key in S:
	d[key] = 0


for key in s:
	d[key] += 1

ans=""
for k, v in sorted(d.items(), key=lambda x: x[0]):
	#print(str(k) + ": " + str(v))
	if int(v)==0:
		ans = s + k
		print(ans)
		exit(0)

#print(sorted(d.items()))


stock=""
for i in range(25, -1, -1):
	k = s[i]
	b=""
	p(i)
	p(k)
	for a in stock:
		p(a)
		if k < a:
			if b!="":
				if a < b: b = a
			else:
				b = a
	if b!="":
		ans = s[:i] + b
		print(ans)
		exit(0)
	stock += k
	p(b)
	#print("")
	




#for i in range(26):
#	if s[i] == S[i]:
#		ans += s[i]
#	else:
#		ans = ans[:-1] + S[i]
#		print(ans)
#		exit(0)

print("-1")

Submission status: Accepted

Solution code:
S = input()
a = [chr(ord('a') + i) for i in range(26)]
for l in S:
    a.remove(l)
if a != []:
    print(S+a[0])
else:
    b = []
    k = 1
    for l in reversed(S):
        b.append(l)
        b.sort()
        if b[-1] != l:
            print(S[0:-k]+b[b.index(l)+1])
            break
        k+=1
    else:
        print(-1)

Submission status: Accepted

Solution code:
s = list(input())
if sorted(s, reverse=True) == s and len(s) == 26:
    print(-1)
    quit()
for i in range(0, 26):
    if chr(97 + i) not in s and len(s) != 26:
        print(''.join(s) + chr(97+i))
        quit()

while len(s) > 0:
    while ord(s[-1]) < ord('z'):
        s[-1] = chr(ord(s[-1])+1)
        if len(s) == len(set(s)):
            print(''.join(s))
            quit()
    del s[-1]

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#
#
# S = input()
#

s = str(input())
# s = 'czyxwvutsrqponmlkjihgfedba'

s_list = list(s)
s_length = len(s)
last_str = s[-1]

alphabet = ['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 s == 'zyxwvutsrqponmlkjihgfedcba':
    print(-1)

elif s_length < 26:
    rest_list = list(set(alphabet) - set(s_list))
    rest_list.sort()
    print(s + rest_list[0])

else:
    trans_list = []
    for i in reversed(range(1,len(s))):
        trans_list.append(alphabet.index(s_list[i]))
        min_trans_list = min(trans_list)

        if alphabet.index(s_list[i-1]) < alphabet.index(s_list[i]):
            last_list = [k for k in trans_list if k > alphabet.index(s_list[i-1])]

            print(s[:i-1] + alphabet[last_list[0]])

            break

Submission status: Accepted

Solution code:
#0. setting
CHR_A = ord("a") #97
NUM_CHR = 26
CHR_LIST = [chr(CHR_A+i) for i in range(NUM_CHR)]

def addChar(s, chr_list):
    for char in chr_list:
        if not(char in s):
            s = s+char
            break
    return s

def removeTail(s):
    for i in range(1,NUM_CHR):
        if ord(s[-1])<ord(s[-2]):
            s = s[:-1]
        else:
            s = s[:-1]
            last_s = s[-1]
            s = s[:-1:1]
            candidate = [chr(i) for i in range(ord(last_s)+1, CHR_A+NUM_CHR)]
            s = addChar(s, candidate)
            break
    return s

def main():
    #1. input
    s = input()

    #sp. output -1 if S='zyx...a'
    if s == ''.join(CHR_LIST[::-1]):
        print(-1)
    
    
    #2. add next char if |S| <= 25
    elif len(s) <= 25:
        s = addChar(s, CHR_LIST)
        print(s)
    
    
    #3. jump next step if |S| == 26
    else:
        s = removeTail(s)
        print(s)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def rev26(s):
    for i in range(len(s) - 1, 0, -1):
        if (s[i] > s[i - 1]):
            chars = sorted(s[i:])
            for j in range(len(chars)):
                if chars[j] > s[i - 1]:
                    return s[0:i - 1] + chars[j]

    return "-1"
    

s = input()

if len(s) == 26:
    print(rev26(s))

else:
    alphabets = "abcdefghijklmnopqrstuvwxyz"
    for i in range(len(s)):
        alphabets = alphabets.replace(s[i], "")

    print(s + alphabets[0])

Submission status: Accepted

Solution code:
import sys
S = []

S = input()

Len = len(S)

Cnt = [0 for i in range(26)]
Chk = 0

S2 = 'abcdefghijklmnopqrstuvwxyz'

if Len == 26:
    for i in range(Len):
        TmpS = S[i]
        for j in range(26):
            if S2[j] == TmpS:
                Cnt[j] += 1
                if Cnt[j] > 1:
                    print('-1')
                    sys.exit()
            break

        
    Cnt = [0 for i in range(26)]
    
    for i in range(26):
        TmpI2 = 25 - i
        TmpI1 = 25 - i - 1
        if TmpI2 <= 0:
            print('-1')
            sys.exit()
            
        TmpS2 = S[TmpI2]
        TmpS1 = S[TmpI1]
        
        TmpS1N = 26
        TmpS2N = 26
        for j in range(26):
            if TmpS2 == S2[j]:
                TmpS2N = j

            if TmpS1 == S2[j]:
                TmpS1N = j
            
            if (TmpS1N < 26) and (TmpS1N < 26):
                break
        
        if TmpS1N < TmpS2N:
            for j in range(26):
                TmpI3 = 25 - j
                TmpS3 = S[TmpI3]
                if TmpS3 == S2[TmpS1N]:
                    break
                for j2 in range(26):
                    if TmpS3 == S2[j2]:
                        TmpS3N = j2
                        
                        if TmpS3N < TmpS1N:
                            Cnt[TmpS3N] = 1
                        break
                        
                    
            
            S = S[:TmpI1]
            Len = len(S)
            Cnt[TmpS1N] = 1
            
            break

                
for i in range(Len):
    TmpS = S[i]
    
    for j in range(26):
        if S2[j] == TmpS:
            Cnt[j] += 1
            if Cnt[j] > 1:
                Chk = 1
            break
    
    if (Chk==1):
        print('-1')
        sys.exit()
        
for i in range(26):
    
    if Cnt[i] == 0:
        S = S + S2[i]
        break

print(S)

Submission status: Accepted

Solution code:
S=input()
row='abcdefghijklmnopqrstuvwxyz'
row=list(row)
if len(S)!=26:
    for letter in S:
        row.remove(letter)
    print(S+row[0])
    
else:
    if S=='zyxwvutsrqponmlkjihgfedcba':
        print(-1)
    else:
        S_=[]
        for i in range(25,1,-1):
            if S[i-1]<S[i]:
                for j in range(i-1):
                    S_.append(S[j])
                x=row.index(S[i-1])
                for j in range(x+1,27,1):
                    if row[j] not in S_:
                        S_.append(row[j])
                        break
                S_=''.join(S_)
                print(str(S_))
                break
        else:
            print(row[row.index(S[0])+1])

Submission status: Accepted

Solution code:
alphabet = [chr(i) for i in range(ord('a'), ord('z') + 1)]
# print(chr(ord('z')+1))
s = input()
ans = ''
if s == 'zyxwvutsrqponmlkjihgfedcba':
    ans = '-1'

elif len(s) == 26:
    pre = '`'
    end = 0
    for x in reversed(s):
        if ord(pre) > ord(x):
            ans = s[:end]
            break
        end -= 1
        pre = x
    for a in alphabet:
        if a not in ans and ord(a) > ord(ans[-1]):
            ans = ans[:len(ans)-1] + a
            break
else:
    for a in alphabet:
        if a not in s:
            ans = s + a
            break
print(ans)

Submission status: Accepted

Solution code:
import copy
S=raw_input()
M=list("abcdefghijklmnopqrsqtuvwxyz")


if len(S)==26:
	if S=="zyxwvutsrqponmlkjihgfedcba":
		print -1
		quit()
	else:
		S2=list(S)
		for i in S2[::-1]:
			idx=S2.index(i)
			for j in M:
				if j>i:
					j_idx=S2.index(j)
					S2[idx]=j
					S2[j_idx]=i
					str="".join(S2)
					if str>S:
						print str[:idx+1]
						quit()
					else:
						S2=list(S)
else:
	for i in S:
		M.remove(i)
	print S+M[0]

Submission status: Accepted

Solution code:
import sys,collections;sys.setrecursionlimit(10**7)
def Is(): return [int(x) for x in sys.stdin.readline().split()]
def Ss(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

abc = "abcdefghijklmnopqrstuvwxyz"
s = S()
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
    exit()
if len(s) < 26:
    for a in abc:
        if not a in s:
            print(s+a)
            exit()
else:
    for i in range(len(s)-1):
        if s[-i-2] < s[-i-1]:
            ans = s[:-i-2]
            t = s[-i-2]
            for a in abc:
                if not a in ans and a > t:
                    print(ans+a)
                    exit()

Submission status: Accepted

Solution code:
S = input()
T = "abcdefghijklmnopqrstuvwxyz"
if len(S) != 26:
    for i in T:
        if i not in S:
            print(S+i)
            exit()
else:
    if S == "zyxwvutsrqponmlkjihgfedcba" :
        print(-1)
    else:
        dic = []
        for i in range(25,-1,-1):
            for j in dic:
                if j > S[i]:
                    print(S[:i]+j)
                    exit()
            dic.append(S[i])
            dic = sorted(dic)

Submission status: Accepted

Solution code:
import math
import itertools
from heapq import heapify, heappop, heappush
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect, bisect_left, bisect_right
from collections import defaultdict, deque


# d = defaultdict(lambda: 0)
# setrecursionlimit(10**7)
# inf = float("inf")


##### stdin ####
def LM(t, r): return list(map(t, r))
def R(): return stdin.readline()
def RS(): return R().split()
def I(): return int(R())
def F(): return float(R())
def LI(): return LM(int,RS())
def LF(): return LM(float,RS())
def ONE_SL(): return list(input())
def ONE_IL(): return LM(int, ONE_SL())
def ALL_IL(): return LM(int,stdin)

##### tools #####
def ap(f): return f.append
def pll(li): print('\n'.join(LM(str,li)))
def pljoin(li, s): print(s.join(li))



##### main #####
def main():

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

	set_al = set([chr(i) for i in range(97,123)])
	set_s = set(S)

	if len(S) != len(set_s):
		print("-1")

	availables = sorted(list(set_al - set_s), reverse = True)

	if availables:
		print(S+str(availables[-1]))
	else:
		f = False
		for i in range(len(S))[::-1]:
			chr_n = ord(S[i])

			while chr_n <= 122:
				if chr(chr_n) not in S:
					S = S[:-1]
					S += chr(chr_n)
					f = True
					break
				chr_n += 1

			if f:
				break
			S = S[:-1]

		print(S)


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
ascii_lowercase='abcdefghijklmnopqrstuvwxyz'

s=input()

if(len(s)<26):
    for c in ascii_lowercase:
        if(s.find(c)<0):
            print(s+c)
            break
elif(s==ascii_lowercase[::-1]):
    print(-1)
else:
    for i in range(25):
        if(s[-i-2]<s[-i-1]):
            t=''.join(sorted(s[-i-2:]))
            j=t.find(s[-i-2])+1
            print(s[:-i-2]+t[j])
            break

Submission status: Accepted

Solution code:
s=input()
t=list(s)
u=list(s)
a=[]
for i in range(26):
    a.append(chr(i+97))
if len(t)!=26:
    flag=True
    for i in range(len(a)):
        if a[i] not in t:
            b=a[i]
            flag=False
            break

    if flag:
        print(-1)
    else:
        print(s+a[i])
else:
    flag2=True
    r=[t[-1]]
    t.remove(t[-1])
    while len(t):

        if r[-1]>t[-1]:
            k=t[-1]
            t.remove(t[-1])
            for i in range(len(r)):
                if r[i]>k:
                    ans=r[i]
                    break

            print("".join(t)+ans)
            flag2=False
            break
        if len(t)==0: break
        r.append(t[-1])
        t.remove(t[-1])

        r=sorted(r)
    if flag2: print(-1)

Submission status: Accepted

Solution code:
S = list(input())

P = set(S)

flag = 0
if len(S) == 26:
    Q = set()
    for i in range(25):
        if ord(S[25 - i]) < ord(S[25 - i - 1]):
            Q.add(ord(S[25 - i]))
            S.pop()
        else:
            while len(Q)>0 and ord(S[25 - i - 1])>min(Q):
                Q.remove(min(Q))
            if len(Q)>0:
                S.pop()
                S.pop()
                S.append(chr(min(Q)))
                flag = 1
                break
            else:
                Z = S[25-i]
                S.pop()
                S.pop()
                S.append(Z)
                flag = 1
                break
else:
    for j in range(26):
        M = chr(97 + j)
        if M in P:
            pass
        else:
            S.append(M)
            flag = 1
            break

if flag == 0:
    print(-1)
else:
    print(''.join(S))

Submission status: Accepted

Solution code:
S= input()
alpha = [chr(i) for i in range(ord('a'), ord('z')+1)]
used = [0] * 26
for i in range(len(S)):
    for j in range(26):
        if S[i] == alpha[j]:
            used[j] = 1
            break
if 0 not in used:
    if S == 'zyxwvutsrqponmlkjihgfedcba':
        print(-1)
    else:
        remvid = []
        for x in range(25,0,-1):
            remvid.append(alpha.index(S[x]))
            if max(remvid) > alpha.index(S[x-1]):
                remvid.sort()
                tmp = 0
                while remvid[tmp] < alpha.index(S[x-1]):
                    tmp += 1
                print(S[:x-1]+alpha[remvid[tmp]])
                break
            else:
                continue
else:
    for x in range(26):
        if used[x] == 0:
            print(S+alpha[x])
            break

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
s = input()
# print(len(s))
alpha = [0] * 26

# if len(s) == 27:
#     print(-1)
# else:
for c in s:
    i = ord(c)-97
    alpha[i] = 1
        # print(c)

flag = True
for i,e in enumerate(alpha):
    if e == 0:
        s += chr(i + 97)
        flag = False
        break

#全ての文字が使われている時
if flag:
    i = len(s) - 1
    while i >= 1:
        alpha[ord(s[i])-97] = 0
        if s[i] > s[i-1]:
            # print(s[i])
            s = s[:i]
            break
        i -= 1
    
    if i == 0:
        print(-1)
    else:
        # print((ord(s[-1])-97))
        # print(ord('x')-97)
        for i,e in enumerate(alpha):
            if e == 0 and i > (ord(s[-1])-97):
                s = s[:-1]
                s += chr(i + 97)
                print(s)
                break
else:
    print(s)

# print(ord("b")-97)

Submission status: Accepted

Solution code:
import numpy as np

s = input()

text = "abcdefghijklmnopqrstuvwxyz"
count = np.zeros(len(text), dtype=np.int)

if(len(s) != len(text)):
    for i in s:
        for j in range(len(text)):
            if(i == text[j]):
                count[j] = 1
                break

    for i in range(len(text)):
        if(count[i] == 0):
            print((s + text[i]))
            exit()
else:
    for i in range(1, len(text) + 1, 1):
        count = np.zeros(len(text), dtype=np.int)
        for j in s[0:-i]:
            for k in range(len(text)):
                if(j == text[k]):
                    count[k] = 1
                    break

        for j in range(len(text)):
            if(s[-i] == text[j]):
                num = j
                break
        for j in range(num+1, len(text), 1):
            if(count[j] == 0):
                print((s[0:-i] + text[j]))
                exit()

print("-1")

Submission status: Accepted

Solution code:
s = input()
d = {0: [], 1:[]}
letters = 'abcdefghijklmnopqrstuvwxyz'
for i in letters:
    d[0].append(i)

curs = ''
ans = []
next = s[0]
c = []
f = False

for i in s:
    curs += i
    d[1].append(d[0].pop(d[0].index(i)))

if len(s) < 26:
    ans = curs + d[0][0]
else:
    while ans == []:
        if s:
            c.append(s[-1])
            s2 = s[:-1]
            c.sort()
            for j in c:
                if s2 + j > s:
                    ans = s2 + j
                    break
            s = s[:-1]
        else:
            ans = -1


print(ans)

Submission status: Accepted

Solution code:
a = input()
b = ["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"]
c = []
d = ["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"]
e = set()
for i in a:
    b.remove(i)
if len(b) > 0:
    print(a+b[0])

else:
    try:
        for j in a:
            c.append(j)
        for l in reversed(range(26)):
            e.add(c[l])
            del c[l]
            if len(c) == 0:
                print(-1)
                raise Exception
            memo = c[l-1]
            for k in range(len(d) - 1):
                if c[l - 1] == d[k]:
                    c[l - 1] = d[k + 1]
                    if c[l - 1] in e:
                        print("".join(c))
                        raise Exception
            c[l-1] = memo
    except Exception:
        pass

Submission status: Accepted

Solution code:
s=input()

ss=[0 for i in range(26)]
for i in range(len(s)):
    for j in range(26):
        if s[i]==chr(97+j):
            ss[j]=1

if len(s)!=26:
        for i in range(26):
            if ss[i]==0:
                s=s+chr(97+i)
                break
        print(s)





else:
    if s=="zyxwvutsrqponmlkjihgfedcba":
        print(-1)
    else:
        for i in range(25):
            if s[24-i] < s[25-i]:
                s=s[:25-i]
                break

        sss=[0 for i in range(26)]
        for i in range(len(s)):
            for j in range(26):
                if s[i]==chr(97+j):
                    sss[j]=1

        for i in range(26):
            if sss[i]==0 and chr(97+i)> s[len(s)-1]:
                s=s[:len(s)-1]+chr(97+i)
                break

        print(s)

Submission status: Accepted

Solution code:
import sys


s = input()
alpha = [chr(i) for i in range(97, 97+26)]
if s == "zyxwvutsrqponmlkjihgfedcba":
    print(-1)
else:
    res = ""
    for i in alpha:
        if i not in s:
            res = i
            break
    if res != "":
        print(s+res)
        sys.exit()

    tmp_res = s
    for i in s[::-1]:
        if i == "z":
            tmp_res = tmp_res[:-1]
        elif i != "z":
            for j in alpha[alpha.index(i)+1:]:
                if tmp_res.count(j) == 0:
                    print(tmp_res.replace(i, j))
                    sys.exit()
            tmp_res = tmp_res[:-1]

Submission status: Accepted

Solution code:
def Next(S):
    if len(S)!=26:
        f=[0 for i in range(26)]
        for i in S:
            f[ord(i)-97]+=1
        t=""
        for i in range(26):
            if f[i]==0:
                t=chr(i+97)
                break
        return (S+t)
    else:
        if S=="zyxwvutsrqponmlkjihgfedcba":
            return (-1)
        else:
            k=0
            for i in range(25):
                if ord(S[25-i])>ord(S[24-i]):
                    k=24-i
                    break
            T=S[:k]
            g=[0 for i in range(26)]
            for i in T:
                g[ord(i)-97]=1
            for n in range(ord(S[k])-97):
                g[n]=1
            g[ord(S[k])-97]=1
            t=""
            #K=[25-i for i in range(26)]
            for i in range(26):
                if g[i]==0:
                    t=chr(i+97)
                    break
            return (T+t)
            return S
s=input()
print(Next(s))
'''
print("############")
for i in range(100):
    print(s)
    s=Next(s)
'''

Submission status: Accepted

Solution code:
s = input()
muximum = 'zyxwvutsrqponmlkjihgfedcba'
if s == muximum:
    print(-1)
else:
    if len(s) == 26:
        d = {c:0 for c in s}
        for i, c in enumerate(reversed(s)):
            for x in range(ord(c), ord('z') + 1):
                if chr(x) not in d:
                    break
            else:
                del d[c]
                continue
            break
        print(s[:-i-1] + chr(x))
    else:
        diff = set(muximum) - set(s)
        print(s + sorted(diff)[0])

Submission status: Accepted

Solution code:
s = input()

lst = ['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']

dic = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6,
       'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13,
       'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20,
       'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

if len(s) < 26:
    for x in s:
        lst.remove(x)
    print(s + lst[0])
    
else:
    tmp = ''
    cnt = 0
    cond = False
    for i in range(26):
        cnt_tmp = dic[s[-1]]
        if cnt <= cnt_tmp:
            tmp += s[-1]
            cnt = cnt_tmp
            s = s[:-1]
        else:
            last = s[-1]
            tmp += last
            s = s[:-1]
            cond = True
            break
            
    if cond:
        print(s + sorted(tmp)[sorted(tmp).index(last) + 1])
    else:
        print(-1)

Submission status: Accepted

Solution code:
s=list(raw_input())
l=len(s)-1
if len(s)<26:
    al = {}
    for i in s:
        al[i] = 1
    while (l >= 0):
        for i in range(97, 97 + 26):
            x = chr(i)
            if al.get(x, -1) == -1 :
                ans = s[:l + 1] + [x]
                if len(s) == 26:
                    ans[-2] = ''
                print ''.join(ans)
                exit()
        al[s[l]] = -1
        l -= 1
    print -1
else:
    al={}
    for i in s:
        al[i]=1
    while(l>=0):
        for i in range(97,97+26):
            x=chr(i)
            if al.get(x,-1)==-1 and x>s[l]:
                ans=s[:l+1] +[x]
                if len(s)==26:
                    ans[-2]=''
                print ''.join(ans)
                exit()
        al[s[l]]=-1
        l-=1
    print -1