# 13.Next Greater Element III

Given a positive **32-bit** integer **n**, you need to find the smallest **32-bit** integer which has exactly the same digits existing in the integer **n** and is greater in value than n. If no such positive **32-bit** integer exists, you need to return -1.

```
Example 1:
Input: 12
Output: 21 

Example 2:
Input: 21
Output: -1
```

## Solution : (Same as next permutation)

```cpp
class Solution
{
public:
    void reverse(vector<int> &v, int start)
    {

        int end = v.size() - 1;

        while (start <= end)
        {
            if (v[start] > v[end])
            {
                swap(v[start], v[end]);
            }
            start++;
            end--;
        }
        return;
    }
    
    int nextGreaterElement(int n)
    {

        vector<int> v;
        while (n > 0)
        {
            int x = n % 10;
            v.insert(v.begin(), x);
            n = n / 10;
        }

        int idx = -1;
        for (int i = v.size() - 1; i > 0; i--)
        {
            if (v[i - 1] < v[i])
            {
                idx = i - 1;
                break;
            }
        }

        if (idx != -1)
        {

            int idx2 = idx + 1;
            for (int i = idx + 1; i < v.size(); i++)
            {
                if (v[i] > v[idx] && v[i] <= v[idx2])
                {
                    idx2 = i;
                }
            }
            swap(v[idx], v[idx2]);
            reverse(v, idx + 1);
        }
        else
        {
            return -1;
        }

        int num = 0;
        for (int i = 0; i < v.size(); i++)
        {
            num = num * 10 + v[i];
            if(num > INT_MAX/10){
                return -1;
            }
        }

        return num;
    }
};
```

**Time Complexity: O(n)**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/arrays/14.next-greater-element-iii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
