The challenge
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
nextBigger(num: 12) # returns 21
nextBigger(num: 513) # returns 531
nextBigger(num: 2017) # returns 2071
If the digits can’t be rearranged to form a bigger number, return -1
(or nil
in Swift):
9 ==> -1
111 ==> -1
531 ==> -1
nextBigger(num: 9) # returns nil
nextBigger(num: 111) # returns nil
nextBigger(num: 531) # returns nil
Test cases
Test.assert_equals(next_bigger(12),21)
Test.assert_equals(next_bigger(513),531)
Test.assert_equals(next_bigger(2017),2071)
Test.assert_equals(next_bigger(414),441)
Test.assert_equals(next_bigger(144),414)
The solution in Python
This problem requires careful manipulation of digits and arrays, similar to other Python challenges like finding the intersection of two arrays or getting the last element of a list .
def next_bigger(n):
# create a list representation of the input integer
arr = list(str(n))
# sort in reverse to get the largest possible number
max_n = int("".join(sorted(arr, reverse=True)))
# sort to get the minimum number
min_n = sorted(arr)
# copy the input to a new variable
m = n
# loop while less than or equal to the max
while m <= max_n:
# increment our number
m += 1
# if found in our min list
if sorted(list(str(m))) == min_n:
# return the new number
return m
# if all else fails, return -1
return -1
An alternative
def next_bigger(n):
# if the number is the same as the reverse
if str(n) == ''.join(sorted(str(n))[::-1]):
# return -1 as it doesn't change
return -1
# keep a new temp variable
a = n
# loop forever
while True:
# increment the number
a += 1
# we have a match!
if sorted(str(a)) == sorted(str(n)):
# return the answer!
return a