Problem · Array

Next and Previous Lexicographic Permutation

Learn this problem
MediumAdobe logoAdobeFULLTIMEONSITE INTERVIEW

Problem 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 direction is "NEXT", produce the next lexicographically greater permutation. If none exists, wrap to the smallest permutation.
  • If direction is "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 nums fits a signed 32-bit integer.
  • direction is exactly "NEXT" or "PREVIOUS".
  • Transform the input array in place using O(1) auxiliary space.

More Adobe problems

drafts saved locally
public int[] adjacentPermutation(int[] nums, String direction) {
    // TODO: mutate nums to the requested adjacent permutation.
}
nums[1,2,2]
direction"NEXT"
expected[2,1,2]
checking account