Problem:
Algorithm:
- Loop from second last character to first character.
- Check if a lexicographically larger character exists after each character.
- If yes, swap character with smallest character present after it which is larger than it.
- Sort the characters after swapped character in non-decreasing order.
Code:
def next_perm(strr):
strr=list(strr)
n=len(strr)
ck=0
for i in range(-2, -1*(n+1), -1):
tmp=strr[i]
for i2 in range(i+1, 0, 1):
if strr[i2]>tmp:
strr[i2], strr[i] = strr[i], strr[i2]
ck=1
strr[i+1::]=sorted(strr[i+1::])
if ck:
break
return strr
n, k = map(int, input().split())
for i in range(k):
a=input().split()
x=next_perm(a)
for ix in range(len(x)-1):
print(x[ix], end=' ')
print(x[-1])
I am getting AC in 2 tasks, WA in other 9. Why?
And when I store numbers as int instead of string, my solution is able to pass 9 tasks. Why does that make a difference?!