Next Greater Element III

Given a positive integer n, find the smallest integer that is greater than n and uses exactly the same digits as n. If no such integer exists, return -1. Example: Input: n = 12 Output: 21 Explanation: 21 is the next greater permutation of the digits 1 and 2. Pattern focus: Next Greater Pattern via next permutation logic.

Input Format

n = positive integer

Output Format

smallest integer greater than n using the same digits, or -1

Constraints

  • 1 <= n <= 2^31 - 1

Examples

Example 1:

Input:

n = 12

Output:

21

Explanation:

Swap to the next lexicographically larger permutation.

Example 2:

Input:

n = 534976

Output:

536479

Explanation:

Find the pivot, swap with the next larger digit, and reverse the suffix.

Loading...
Next Greater Element III - Monotonic Stack Queue