/31. Next Permutation

31. Next Permutation

Medium
Arrays44.9% acceptance

Given a list of integers sequence, rearrange the elements to produce the next lexicographically greater permutation. If no such permutation exists (the sequence is sorted in descending order), rearrange the sequence to the lowest possible order (sorted in ascending order). The operation must be performed in-place, using only constant extra memory.

Example 1

Input: [4, 5, 2, 3]

Output: [4, 5, 3, 2]

Explanation: The next lexicographical permutation after [4, 5, 2, 3] is [4, 5, 3, 2].

Example 2

Input: [2, 2, 1]

Output: [1, 2, 2]

Explanation: No greater permutation exists, so return the lowest possible order.

Example 3

Input: [1, 3, 2]

Output: [2, 1, 3]

Explanation: The next permutation after [1, 3, 2] is [2, 1, 3].

Constraints

  • 1 <= len(sequence) <= 100
  • 0 <= sequence[i] <= 100 for all valid i
Python (current runtime)

Case 1

Input: [7, 6, 5]

Expected: [5, 6, 7]

Case 2

Input: [1, 4, 3, 2]

Expected: [1, 4, 2, 3]

Case 3

Input: [3, 1, 4, 2]

Expected: [3, 2, 1, 4]

Case 4

Input: [2, 3, 3]

Expected: [3, 2, 3]

Case 5

Input: [0, 1, 0]

Expected: [1, 0, 0]