Suppose we have an array A of positive integers (not necessarily unique), we have to find the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot possible, then return the same array. So if the array is like [3,2,1], then the output will be [3,1,2], by swapping 2 and 1
To solve this, we will follow these steps −
- n := size of A
- for left in range n – 2 down to -1
- if left = -1, then return A, otherwise when A[left] > A[left + 1], then break
- element := 0, index := 0
- for right in range left + 1 to n
- if A[right] < A[left] and A[right] > element, then
- element = A[right]
- index := right
- if A[right] < A[left] and A[right] > element, then
- swap A[left] and A[index]
- return A
Let us see the following implementation to get better understanding −
Example
class Solution(object): def prevPermOpt1(self, A): n = len(A) for left in range(n-2,-2,-1): if left == -1: return A elif A[left]>A[left+1]: break element = 0 index = 0 for right in range(left+1,n): if A[right]<A[left] and A[right]>element: element = A[right] index = right temp = A[left] A[left] = A[index] A[index] = temp return A ob = Solution() print(ob.prevPermOpt1([4,2,3,1,3]))
Input
[4,2,3,1,3]
Output
[4, 2, 1, 3, 3]