Rearrange Array to Next Greater Sequence
Arrays & HashingAuto-graded · 22 test casesLast 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 <= 1000 <= 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?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to think of the array as representing a number: to get the next larger number, we need to increase the rightmost digit possible by the smallest amount possible.
The algorithm works in three phases:
-
Locate the pivot position: Scan from right to left to find the first index
iwherenums[i] < nums[i + 1]. Everything to the right of this position is in non-increasing order, which is the largest possible arrangement for that suffix. This means positioniis the rightmost location that must increase to form a greater permutation. -
Find the replacement: Scan the suffix from right to left to find the first element
nums[j]that is strictly greater thannums[i]. Since the suffix is non-increasing, this element is the smallest value greater thannums[i], and choosing the rightmost occurrence ensures the suffix remains non-increasing after the swap. -
Swap and reverse: Swap
nums[i]withnums[j], then reverse the entire suffix starting ati + 1. The suffix is still non-increasing after the swap (its largest arrangement), so reversing it produces the smallest arrangement, ensuring the overall increase is minimal.
When no pivot exists (the entire array is non-increasing), it represents the largest permutation. Reversing the entire array produces the smallest permutation, completing the wrap-around.
Why It Works
- The longest unchanged prefix maximizes locality: any change earlier in the array would produce a larger jump than necessary.
- Choosing the smallest greater value at position
iensures the minimal increase at that position. - Reversing the suffix (rather than sorting it) works because we know it's non-increasing, making reversal equivalent to sorting in O(n) time.
- Duplicates are handled correctly through strict inequality checks: equal values never trigger a pivot, and equal values are never selected as replacements.
Complexity
Time complexity: O(n), where n is the length of the array. Each phase (finding the pivot, finding the successor, and reversing) scans at most the entire array once.
Space complexity: O(1). Only a constant number of index variables are used; all modifications happen in-place.
Solution Code
from typing import List
def rearrange_to_next(nums: List[int]) -> List[int]:
# Find the rightmost position where the sequence stops increasing
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
# Find the smallest element greater than nums[i] from the right
j = len(nums) - 1
while nums[j] <= nums[i]:
j -= 1
# Swap to increase position i minimally
nums[i], nums[j] = nums[j], nums[i]
# Reverse the suffix to get its smallest arrangement
left, right = i + 1, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums