[Geeks for Geeks] Next Permutation

Next Permutation

Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
class Solution{
public:
vector<int> nextPermutation(int N, vector<int> arr){
next_permutation(begin(arr), end(arr));
return arr;
}
};
  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution{
public:
vector<int> nextPermutation(int N, vector<int> arr){
int pos = N - 1;
for(; pos > 0; pos--) {
if(arr[pos] <= arr[pos - 1]) continue;
sort(begin(arr) + pos, end(arr));

for(int i = pos; i < N; i++)
if(arr[pos - 1] < arr[i]) {
swap(arr[pos - 1], arr[i]);
return arr;
}
}

sort(begin(arr), end(arr));
return arr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/next-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.