<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:
        array = [c for c in str(n)]
        length = len(array)
        
        # Step 1: Find the first decreasing element from the right
        i = length - 2
        while i >= 0 and array[i] >= array[i + 1]:
            i -= 1
        print(array[i])
        
        # If no such element is found, return -1
        if i == -1:
            return -1
        
        # Step 2: Find the smallest element larger than array[i] to the right of i
        j = length - 1
        while array[j] <= array[i]:
            j -= 1
        print(array[j])
        
        # Step 3: Swap elements at i and j
        print(array)
        array[i], array[j] = array[j], array[i]
        print(array)
        
        # Step 4: Reverse the suffix starting at i+1
        print(array)
        array = array[:i + 1] + array[i + 1:][::-1]
        print(array)
        # Step 5: Convert back to an integer
        new_n = int("".join(array))
        
        # Step 6: Check if it exceeds 32-bit integer limit
        if new_n >= (2**31):
            return -1
        
        return new_n

16500