I'm solving a code wars kata problem but am struggling to figure out how to make my function more efficient because I keep getting stuck on the test cases that involve large numbers.
The instructions for the kata are as follows:
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 2071If the digits can't be rearranged to form a bigger number, return -1 (or nil in Swift):
9 ==> -1 111 ==> -1 531 ==> -1
(I'm pretty sure) my code is bug free and the only problem it has is its efficiency:
from itertools import permutations
def next_bigger(n):
possible_nums = [int(''.join(p)) for p in permutations(str(n))]
possible_nums = list(dict.fromkeys(possible_nums))
print(possible_nums)
if possible_nums.index(n)+1 == len(possible_nums):
return -1
else:
return possible_nums[possible_nums.index(n)+1]
I don't know if the permutation() function is whats causing the issue or the list(dict.fromkeys(possible_nums)) but I can't seem to find a more efficient way to find each permutation of the number, n. Any help on whether I should restructure the entire function or just replace some bits of code to make it more efficient is much appreciated!