Ctrl K

Next Bigger From the Same Digits

Medium
You are given a positive integer number. Rearrange its digits to get the smallest number that is strictly greater than number. Each digit is used exactly as many times as it appears in number. If no such number exists, or it is greater than 2³¹ − 1 (it does not fit in a signed 32-bit integer), return -1.
Example 1
number=1432 → 2134

The tail 432 is already as large as it gets. Replace the 1 with the smallest larger digit from the tail, 2, and put the rest (1, 3, 4) in ascending order: 2134.

Example 2
number=5510 → -1

The digits are already in descending order, so nothing larger can be built: -1.

Example 3
number=1999999999 → -1

The next number from the same digits is 9199999999, which does not fit in a 32-bit integer, so the answer is -1.

Constraints
  • 1 ≤ number ≤ 2³¹ − 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWord Topping Duel HardLongest Mirror Fragment MediumNumber in Roman Numerals MediumMultiplying Digit Strings MediumWords in Reverse Order Medium
loading Python…
Input
number=1432
Expected
2134

Run checks the first 3 tests in your browser. Submit checks all 53 tests on the server, hidden ones included.