<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p>

<p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 12
<strong>Output:</strong> 21
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 21
<strong>Output:</strong> -1
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution:
    def nextGreaterElement(self, n: int) -> int:
        threshold = 2**31-1
        nums = list(str(n))
        i = len(nums)-2
        # find a swappable pair
        while i>=0 and nums[i+1]<=nums[i]:
            i-=1
        # find the first number that can be swapped
        if i>=0:
            j = len(nums)-1
            while nums[j]<=nums[i]:
                j-=1
            nums[i],nums[j] = nums[j],nums[i]
        
        # reverse remaining numbers 
        i +=1
        j = len(nums)-1
        while i<j:
            nums[i],nums[j] = nums[j],nums[i]
            i+=1
            j-=1
        res = 0
        for c in nums:
            res = res*10+int(c)
        if res<=n or res>threshold:
            return -1
        # print(nums)
        return res
16300