Previous Permutation With One Swap — LeetCode 1053 Python Solution
- Problem
- #1053
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- arr = [3,2,1]
- Output
- [3,1,2]
- Explanation
- Swapping 2 and 1.
Python solution
class Solution:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
n = len(arr)
for i in range(n - 1, 0, -1):
if arr[i - 1] > arr[i]:
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 arrComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1053. Previous Permutation With One Swap is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1053. Previous Permutation With One Swap?
- LeetCode 1053. Previous Permutation With One Swap is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1053. Previous Permutation With One Swap?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 1053. Previous Permutation With One Swap?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1053. Previous Permutation With One Swap cover?
- LeetCode 1053. Previous Permutation With One Swap is tagged Greedy and Array on LeetCode.