Reference: LeetCode
Difficulty: Medium

Problem

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

Example:

1
2
3
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

Analysis

Brute-Force

Generate every possible permutation and do comparison.

Time: $O(N!)$
Space: $O(N)$

Single Pass

Note: This problem is good for index manipulation practice.

Idea: LeetCode Solution

Try these examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void nextPermutation(int[] nums) {
// assume nums is not null
int n = nums.length;
// find the pair
int i = n - 1;
while (i > 0 && nums[i - 1] >= nums[i]) {
--i;
}
// find the one
if (i != 0) {
int j = n - 1;
while (j >= i && nums[j] <= nums[i - 1]) {
--j;
}
swap(nums, i - 1, j);
}
// reverse
reverse(nums, i, n - 1);
}

private void reverse(int[] nums, int lo, int hi) {
// assume valid
int n = hi - lo + 1;
for (int i = 0; i < n / 2; ++i) {
swap(nums, lo + i, hi - i);
}
}

private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}

Time: $O(N)$
Space: $O(1)$