![]() |
VOOZH | about |
Given a string s representing a non-negative integer, find the lexicographically previous permutation of its digits. Each digit of s must be used exactly once, and the resulting number must not contain leading zeros.
Examples:
Input: s = "4321"
Output: "4312"
Explanation:The lexicographically previous permutation of "4321" is "4312".Input: s = "1234"
Output: "-1"
Explanation: The string "1234" is sorted in ascending order, so no previous permutation exists.
Table of Content
The idea is to generate all possible permutations of the digits of s using recursion (backtracking). For each permutation, we check whether it is valid,. Among all valid permutations, we keep track of the largest one. If no valid permutation exists, return “-1”.
4312
Instead of generating all permutations, we directly construct the previous permutation. We first find the pivot, the first index from the right where s[i] > s[i+1]. This is the point where the number can be reduced.
Consider the input: s = "534976"
Step 1: Traverse from right and find the first index i such that s[i] > s[i + 1].
Step 2: From the right side of pivot, find the largest digit smaller than pivot digit.
Step 3: Swap the pivot digit with the selected digit.
Step 4: Reverse the suffix after the pivot. Since the suffix is already in increasing order, reversing it makes it descending and gives the largest possible arrangement.
Step 5: The resulting string is: 534967
Therefore, the lexicographically previous permutation of "534976" is: 534967
534967