-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61) Find next greater number with same set of digits.cpp
69 lines (58 loc) · 1.43 KB
/
61) Find next greater number with same set of digits.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
vector<int> nextPermutation(int N, vector<int> arr){
/*
Steps to solve
1) Find longest non-incresing sequence suffix
2) Find the pivot
3) Find the rightmost successor of pivot
4) Swap right most successor and pivot value
5) Reverse the suffix sequence
*/
int pivot = -1;
//step 2
for(int i=N-2; i>=0; i--){
if(arr[i] < arr[i+1]){
pivot = i;
break;
}
}
if(pivot == -1){
reverse(arr.begin(), arr.end());
return arr;
}
for(int i=N-1; i>pivot; i--){
if(arr[i]>arr[pivot]){
swap(arr[i], arr[pivot]);
break;
}
}
reverse(arr.begin()+pivot+1, arr.end());
return arr;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N;
cin>>N;
vector<int> arr(N);
for(int i = 0;i < N;i++)
cin>>arr[i];
Solution ob;
vector<int> ans = ob.nextPermutation(N, arr);
for(int u: ans)
cout<<u<<" ";
cout<<"\n";
}
return 0;
}
// } Driver Code Ends