Previous Permutation With One Swap — LeetCode 1053 Python Solution

MediumGreedyArray
Problem
#1053
Pattern
Greedy
Reading time
2 min

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

Python
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 arr

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview