
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Previous Permutation With One Swap in Python
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]
- Related Articles
- Program to find Lexicographically Smallest String With One Swap in Python
- Check if array can be sorted with one swap in Python
- Largest number with one swap allowed in C++
- Swap two variables in one line in using Python?
- Next Permutation in Python
- Permutation and Combination in Python?
- Maximum Swap in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Swap two variables in one line in Java
- Fair Candy Swap in Python
- Swap two variables in one line using C#
- Swap two variables in one line in C/C+
- Swap two variables in one line in using Java
- Swap Consecutive Even Elements in Python
- Python Pandas - Return the label from the index or if not present, the previous one

Advertisements