PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'''
To solve this problem, we need to find the next smaller permutation of the digits of a given number n. Here's the step-by-step algorithm:
Identify the pivot point:
Traverse the number from right to left to find the first digit that is larger than the digit to its right. This digit is the "pivot".
Find the largest digit to the right of the pivot that is smaller than the pivot:
This is the digit we will swap with the pivot to make the number smaller.
Swap the pivot with this largest smaller digit:
This will give us a smaller number.
Sort the digits to the right of the pivot in descending order:
This is because we want the largest possible number smaller than the original number.
Handle special cases:
If no pivot is found, it means the digits are in ascending order and there's no smaller permutation possible, so return -1.
If the resultant number after swapping starts with a zero, it's not valid because it would be smaller than any number without leading zeroes.
Here's the Python implementation of this approach:
'''
def nextsmaller(n):
digits = list(str(n))
length = len(digits)
# Step 1: Find the pivot
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run