Problem · Array
Next and Previous Lexicographic Permutation
Learn this problemProblem statement
Given an integer array nums and a direction direction, transform nums in place to its adjacent lexicographic permutation and return the transformed array.
- If
directionis"NEXT", produce the next lexicographically greater permutation. If none exists, wrap to the smallest permutation. - If
directionis"PREVIOUS", produce the previous lexicographically smaller permutation. If none exists, wrap to the largest permutation. - Duplicate values are distinct occurrences. The swap candidate must be strictly greater than the pivot for
"NEXT"and strictly smaller for"PREVIOUS".
The direction is always one of the two uppercase strings above.
Function
adjacentPermutation(nums: int[], direction: String) → int[]Examples
Example 1
nums = [1,2,2]direction = "NEXT"return = [2,1,2]The next distinct lexicographic arrangement after [1,2,2] is [2,1,2].
Example 2
nums = [1,2,3]direction = "PREVIOUS"return = [3,2,1]The input is the smallest permutation, so the previous operation wraps to the largest permutation.
Constraints
1 <= nums.length <= 100000.- Every value in
numsfits a signed 32-bit integer. directionis exactly"NEXT"or"PREVIOUS".- Transform the input array in place using
O(1)auxiliary space.