<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:
        """ 

        3142
        3124 x
        3421 x
        3214 ok
        
        procced = [2, 4]
          i
        3 1 4 2
        3 2 1 4
        """
        n_str = str(n)
        LEN = len(n_str)
        processed = []
        for i in range(LEN-1, -1, -1):
            num = int(n_str[i])
            bisect.insort(processed, num)
            next_greater_index = bisect.bisect_right(processed, num)

            if next_greater_index == len(processed):
                continue
            else:
                next_greater_num = processed.pop(next_greater_index)
                joined = "".join([str(p) for p in processed])
                next_greater_str = "".join([n_str[:i], str(next_greater_num), joined])
                next_greater = int(next_greater_str)
                MAX_INT = 2 ** 31 - 1
                if next_greater > MAX_INT:
                    return -1
                return next_greater
        
        return -1


16500