find next small or big number

December 2018 1 minute read

Find the next small number

There is a very interesting problem.

Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.

Next smaller number with the same digits

def next_smaller(n):
    s = list(str(n))
    # find the pivot
    i = j = len(s) - 1
    while i > 0 and s[i - 1] <= s[i]:
        i -= 1
    # if pivot is -1 means it is descending e.g. 1,2,3,4,5
    # which means it is already the smallest
    if i <= 0: return -1
    # find the substitute of pivot
    while s[j] >= s[i - 1]:
        j -= 1
    # replace pivot with substitute
    s[i - 1], s[j] = s[j], s[i - 1]
    s[i:] = reversed(s[i:])
    # there is no number start with zero
    if s[0] == '0': return -1
    return int(''.join(s))