Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it to the lowest possible order (i.e., sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Input: nums = [1,2,3] Output: [1,3,2]
Input: nums = [3,2,1] Output: [1,2,3]
Input: nums = [1,1,5] Output: [1,5,1]
i
.j
.i+1
to the end of the array to get the next lexicographically smallest permutation.def nextPermutation(nums):
n = len(nums)
if n <= 1:
return
# Step 1: Find the first decreasing element from the end
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
# Step 2: If no decreasing element is found, reverse the whole array
if i == -1:
nums.reverse()
return
# Step 3: Find the element just larger than nums[i] to swap with
j = n - 1
while nums[j] <= nums[i]:
j -= 1
# Step 4: Swap elements at i and j
nums[i], nums[j] = nums[j], nums[i]
# Step 5: Reverse the sub-array from i+1 to the end
nums[i + 1:] = reversed(nums[i + 1:])
# Example Usage:
nums = [1, 2, 3]
nextPermutation(nums)
print(nums) # Output: [1, 3, 2]
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?