# 12825번. Next Permutation
importsysinput=sys.stdin.readlinen=int(input())nList=list(map(int,input().split()))i=n-1whilei>0andnList[i-1]>=nList[i]:i-=1j=n-1whilenList[i-1]>=nList[j]:j-=1nList[i-1],nList[j]=nList[j],nList[i-1]tList=[nList[k]forkinrange(i)]forkinrange(j,n):tList.append(nList[k])ifabs(i-1-k)>1:forkinrange(j-1,i-1,-1):tList.append(nList[k])print(*tList)