Pretty clear solution and explanation! Thanks for sharing. I write it into python.

def nextGreaterElement(self, n): s=list(str(n)) i=len(s)-1 while i>0: if int(s[i-1])<int(s[i]): break i-=1 if i==0:return -1 smallest=i x=int(s[i-1]) for j in range(i+1,len(s)): if int(s[j])>x and int(s[smallest])>=int(s[j]): smallest=j s[smallest],s[i-1]=s[i-1],s[smallest] temp=s[i:] temp.sort() res=''.join(s[:i]) res+=''.join(temp) res=int(res) return res if res>int(n) and res<2147483647 else -1Next Greater Element III