Next Greater Element III

Given a positive integer n, find the smallest integer that has exactly the same digits as n and is greater than n. If there is no such integer, or it does not fit in a 32-bit signed integer, return -1.

30:00

Next Greater Element III
medium
Free written solution
Topics
Companies

Given a positive integer n, find the smallest integer that has exactly the same digits as n and is greater than n. If there is no such integer, or it does not fit in a 32-bit signed integer, return -1.

Example 1:
Input: {"n":12}
Output: 21
Constraints:
  • 1≤n≤231−11 \leq n \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":12}

Split 12 into digits. The next larger number with the same digits changes as little as possible on the right, so the search starts at the last digit.

■ non-increasing tail■ pivot i■ swap partner j

Digits as a staircase: bar height = digit value

1

0

2

1

32-bit limit check

Candidate not built yet
Variables
VariableValue
digits12
i-
j-
DepthFunction Call
Stack empty
0/8