Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-341

Previous Permutation

Problem

Return the previous lexicographically smaller permutation of the list nums, or the largest permutation when nums is already the smallest.

Find the rightmost descent, swap its first element with the largest smaller value to its right, and reverse the suffix. Return a new list and handle duplicates.

Hint

It mirrors next permutation with both comparisons reversed.

Test cases

case 1
in: [[1,3,2]]
expected: [1,2,3]
case 2
in: [[1,2,3]]
expected: [3,2,1]
case 3
in: [[2,3,1]]
expected: [2,1,3]
case 4
in: [[1,1,5]]
expected: [5,1,1]
case 5
in: [[1]]
expected: [1]
Starter codePython
def previous_permutation(nums):
    # Your code here
    pass

5 test cases · run your code against them in the editor