KatInterview

Rearrange Array to Next Greater Sequence

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingarrayspermutationsin-place

Last updated

Tests in-place array manipulation to transform a sequence into its immediate lexicographic successor, wrapping to the smallest arrangement when needed.

You are given an array of integers nums. Your task is to rearrange the elements in-place so that the array represents the smallest permutation that is strictly greater than the current arrangement in lexicographic order.

When no such greater arrangement exists (the array is sorted in non-ascending order), rearrange it to the smallest possible permutation (sorted in non-descending order).

You must solve this problem in-place using only constant extra space.

Constraints

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

Examples

Example 1

Input: rearrange_to_next([1, 2, 3])

Output: [1, 3, 2]

Example 2

Input: rearrange_to_next([3, 2, 1])

Output: [1, 2, 3]

Example 3

Input: rearrange_to_next([1, 1, 5])

Output: [1, 5, 1]

Hints

Hint 1

Think about which position needs to change to produce the next greater arrangement. Scanning from right to left, where does the sequence stop being non-increasing?

Hint 2

Once you've identified the position that must increase, what's the smallest value from the remaining elements that can replace it?

Hint 3

After making the swap, how should the elements to the right be arranged to ensure the result is the very next permutation and not something larger?