31. Next Permutation
Asked at 30Meta80Bloomberg69Microsoft67Amazon64Google61Infosys63Accenture61PornHub100Airtel77Pwc73Adobe69Meesho67Stripe64HashedIn62Walmart Labs60Rubrik59ServiceNow55Samsung53Flipkart52tcs50Deloitte50Cognizant48Citadel47Oracle45DoorDash45IBM44Intuit43Visa39Uber30Goldman Sachs28
Problem
Rearrange nums in place into the next lexicographically greater permutation of its values. If it is already the largest permutation, wrap around to the smallest one (ascending order).
Example: [1,2,3] → [1,3,2]; [3,2,1] → [1,2,3]; [1,1,5] → [1,5,1]
Constraints: O(1) extra space.
From the right, find the first index i with a[i] < a[i+1] (the "pivot"). Swap it with the rightmost element larger than it, then reverse the suffix (it was descending → make it ascending). No pivot → reverse the whole array.
1 3 5 4 2 pivot 3 (3 < 5), rightmost > 3 is 4
1 4 5 3 2 swap
1 4 2 3 5 reverse suffix after pivot
Complexity: O(n) time, O(1) space.
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
j = len(nums) - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = reversed(nums[i + 1:])
for a, b in (([1, 2, 3], [1, 3, 2]), ([3, 2, 1], [1, 2, 3]), ([1, 1, 5], [1, 5, 1]), ([1, 3, 5, 4, 2], [1, 4, 2, 3, 5])):
Solution().nextPermutation(a)
assert a == b
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
if (i >= 0) {
int j = nums.length - 1;
while (nums[j] <= nums[i]) j--;
swap(nums, i, j);
}
for (int l = i + 1, r = nums.length - 1; l < r; l++, r--) swap(nums, l, r);
}
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
func nextPermutation(nums []int) {
i := len(nums) - 2
for i >= 0 && nums[i] >= nums[i+1] {
i--
}
if i >= 0 {
j := len(nums) - 1
for nums[j] <= nums[i] {
j--
}
nums[i], nums[j] = nums[j], nums[i]
}
for l, r := i+1, len(nums)-1; l < r; l, r = l+1, r-1 {
nums[l], nums[r] = nums[r], nums[l]
}
}