Menu
CoddyTech

Next Permutation

You get an array of integers nums, and values may repeat. Picture every distinct arrangement of these values, sorted in dictionary order: compare two arrangements at the first index where they differ, and the one with the smaller value there comes first. Return the arrangement that comes right after nums in that order.

If nums is already the largest arrangement, there is none after it: return the smallest one, which is the values sorted in increasing order. Aim for O(n) time and O(1) extra memory.

Function

nextPermutation(nums: integer-array) → integer-array
numsinteger-array
the current arrangement of values
Returnsinteger-array
the next arrangement in dictionary order, or the values sorted in increasing order if nums is the largest

Constraints

  • 1 ≤ nums.length ≤ 5000
  • 0 ≤ nums[i] ≤ 1000

Examples

Input
nums = [2, 5, 4, 1]
Output
[4, 1, 2, 5]
Explanation
The tail 5, 4, 1 is falling, so the 2 in front of it must grow. The smallest tail value above 2 is 4; put it there and the rest in increasing order: [4, 1, 2, 5].
challenge icon

Follow-up

How would you find the previous arrangement instead, the one that comes right before nums in dictionary order?

Reset code
def nextPermutation(nums):
    # Write code here

Test #1

Test #2

Test #3

Argument

nums = [2, 5, 4, 1]

Expected Output

[4, 1, 2, 5]