Medium · Math

Next Greater Element III

Given a positive integer n (1 ≤ n ≤ 2³¹ − 1), return the smallest integer greater than n that uses exactly the same digits, or −1 if no such integer exists or it does not fit in a signed 32-bit integer.

Examples

Example 1

n = 12443322

Output: 13222344

Example 2

n = 21 (none)

Output: -1 (no larger permutation)

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Math problems