Previous Permutation With One Swap Problem
Description
LeetCode Problem 1053.
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array.
Note that a swap exchanges the positions of two numbers arr[i] and arr[j]
Example 1:
Input: arr = [3,2,1]
Output: [3,1,2]
Explanation: Swapping 2 and 1.
Example 2:
Input: arr = [1,1,5]
Output: [1,1,5]
Explanation: This is already the smallest permutation.
Example 3:
Input: arr = [1,9,4,6,7]
Output: [1,7,4,6,9]
Explanation: Swapping 9 and 7.
Constraints:
1 <= arr.length <= 10^41 <= arr[i] <= 10^4
Solution
Approach: Greedy
To get a smaller array we have to move a smaller value to the left of a larger one. To keep the result as large as possible, the change should happen as far to the right as we can, and the value that moves in should be as large as possible.
Scan from the right for the first descent, an index i with arr[i - 1] > arr[i]. Everything after i - 1 is non-decreasing, so no swap inside that suffix can make the array smaller; position i - 1 is the rightmost place we can improve, and it must receive a smaller value from its right. If there is no descent, the array is already the smallest permutation and we return it unchanged.
Which value should go to i - 1? The largest one in the suffix that is still smaller than arr[i - 1]. Since the suffix is sorted, scanning it from the right finds that value first. The tricky case is duplicates: if that value occurs several times, swap with its leftmost copy. The bigger arr[i - 1] then lands as far left as possible, which keeps the result larger. For [3, 1, 1, 3] the answer is [1, 3, 1, 3], not [1, 1, 3, 3]. In code, while scanning from the right we skip any j with arr[j] == arr[j - 1].
Complexity: O(n) time and O(1) extra space.
class Solution:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
n = len(arr)
# The first descent from the right: arr[i - 1] is the value to make smaller.
for i in range(n - 1, 0, -1):
if arr[i - 1] > arr[i]:
# arr[i:] is non-decreasing. Take the largest value below arr[i - 1],
# and of equal copies the leftmost one (skip j while arr[j] == arr[j - 1]).
for j in range(n - 1, i - 1, -1):
if arr[j] < arr[i - 1] and arr[j] != arr[j - 1]:
arr[i - 1], arr[j] = arr[j], arr[i - 1]
return arr
return arr # no descent: already the smallest permutation