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
.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1
.
Example 1:
Input: n = 12 Output: 21
Example 2:
Input: n = 21 Output: -1
Constraints:
1 <= n <= 231 - 1
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for finding the next greater element involves checking every possible arrangement of the digits in the original number. We generate all possible numbers that can be formed using the same digits and see if any are both larger than the original number and the smallest amongst the numbers larger than the original number.
Here's how the algorithm would work step-by-step:
def next_greater_element_brute_force(number):
string_representation = str(number)
import itertools
permutations = list(itertools.permutations(string_representation))
greater_elements = []
for permutation in permutations:
arranged_number = int("".join(permutation))
# Need to make sure the arranged number is greater than the original
if arranged_number > number:
greater_elements.append(arranged_number)
if not greater_elements:
return -1
# Need to find the smallest of the greater elements
smallest_greater_element = min(greater_elements)
#Check for 32 bit integer overflow
if smallest_greater_element > (2**31 - 1):
return -1
return smallest_greater_element
The key idea is to find the smallest number that's bigger than the given number by rearranging its digits. We want to avoid checking every possible rearrangement by working backwards from the end of the number and making a single, smart swap.
Here's how the algorithm would work step-by-step:
def next_greater_element_iii(number):
number_string = str(number)
length = len(number_string)
# Find the first digit from right that is smaller than the digit to its right.
for index in range(length - 2, -1, -1):
if number_string[index] < number_string[index + 1]:
break
else:
return -1
# If no such digit is found, it's the largest possible number.
pivot_index = index
# Find the smallest digit to the right of pivot_index that is greater than digit at pivot_index.
for index in range(length - 1, pivot_index, -1):
if number_string[index] > number_string[pivot_index]:
swap_index = index
break
# Swap the pivot digit with the found digit.
number_string_list = list(number_string)
number_string_list[pivot_index], number_string_list[swap_index] = number_string_list[swap_index], number_string_list[pivot_index]
# Sort the digits to the right of the pivot_index in ascending order.
number_string_list[pivot_index + 1:] = sorted(number_string_list[pivot_index + 1:])
result_string = "".join(number_string_list)
# Handle potential overflow by checking against max 32-bit integer.
try:
result = int(result_string)
if result > 2**31 - 1:
return -1
else:
return result
except ValueError:
return -1
Case | How to Handle |
---|---|
Input integer is 0 | Convert to string and handle like other numbers; if no next greater exists, return -1 as specified. |
Input integer is negative | The problem statement specifies a positive 32-bit integer as input, so throw an IllegalArgumentException. |
Input integer is already the largest possible permutation | Return -1 since no greater permutation is possible. |
Input integer consists of all 9s (e.g., 999999999) | Return -1, as it's already the largest possible integer with those digits. |
Input integer leads to integer overflow when calculating the next greater element | Check for potential overflow after the digit swap and reversion steps and before returning by comparing result with Integer.MAX_VALUE. |
Input integer with only two digits and they are in descending order | Swap and reverse the two digits to obtain the next greater element, e.g., 21 becomes 12. |
Input integer is a single-digit number | Return -1, as there is no greater number that can be formed with a single digit. |
Input integer has leading zeros after permutation | After the permutation, ensure to parse the output as an integer and return, which will automatically remove leading zeros. |