Next Greater Element III

Medium

Description

Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. The result must fit in 32-bit integer.

Examples

Input:n = 12
Output:21
Explanation:

21 is next greater with same digits.

Input:n = 1234
Output:1243
Explanation:

To find the next greater number with same digits, the task requires find the rightmost digit that can be increased. Starting from right: 4 can't be increased, 3 can be swapped with 4 to get 1243, which is the smallest number greater than 1234 using the same digits.

Input:n = 4321
Output:-1
Explanation:

The digits are arranged in descending order (4321), which means this is already the largest possible number that can be formed using these digits. No greater arrangement exists, so returning -1.

Constraints

  • 1 ≤ n ≤ 2^31 - 1

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!