arrays
two-pointers
greedy

Given an integer array nums, return the lexicographically next greater permutation of its values.

If nums is already the highest possible permutation, return the lowest possible ordering instead (ascending order).

Unlike the classic LeetCode version that mutates the array in place and returns void, this judge is functional-style: return the resulting int[] directly.

Input / output

  • Input: nums: int[]
  • Output: int[]

Examples

  1. nums = [1,2,3] returns [1,3,2].
  2. nums = [3,2,1] returns [1,2,3].
  3. nums = [1,1,5] returns [1,5,1].

Constraints

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100

Follow-up Can you explain why the suffix to the right of the pivot is guaranteed to be non-increasing, and therefore can be reversed instead of fully sorted?

Examples

Example 1

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2

Input: nums = [3,2,1]
Output: [1,2,3]

Example 3

Input: nums = [1,1,5]
Output: [1,5,1]
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.