> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/strings-arrays-and-2-pointers/untitled.md).

# 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
```

```java
class Solution {
    public int nextGreaterElement(int n) {
        String number = Integer.toString(n);
        char[] str = number.toCharArray();
        boolean anyChange = false;
        for (int i = str.length - 2; i >= 0; i--) {
            if (str[i] < str[i + 1]) {
                // Finding element just greater than str[i] in str[i+1...]
                int j = i + 1;
                while (j < str.length && str[j] > str[i])
                    j++;
                j--;
                // Now swap digits at i & j
                char t = str[i];
                str[i] = str[j];
                str[j] = t;
                // Now reverse the part str[i+1...]
                int p1 = i + 1, p2 = str.length - 1;
                while (p1 < p2) {
                    char temp = str[p1];
                    str[p1] = str[p2];
                    str[p2] = temp;
                    p1++;
                    p2--;
                }
                anyChange = true;
                break;
            }
        }
        if (!anyChange)
            return -1;
        else {
            String num = new String(str);
            return (Long.parseLong(num) > Integer.MAX_VALUE ? -1 : Integer.parseInt(num));
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://mayanktyagi3111.gitbook.io/interview-prep/strings-arrays-and-2-pointers/untitled.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.
