class Solution:
def nextGreaterElement(self, n: int) -> int:
s = list(str(n))
m = s[-1]
ans = -1
for i in range(len(s) - 2, -1, -1):
if s[i] < m:
new = min([c for c in s[i:] if c > s[i]])
left = s[i:]
left.remove(new)
ans = int(''.join(s[:i] + [new] + sorted(left)))
break
else:
m = s[i]
if ans <= 2147483647:
return ans
return -1