Skip to content

Commit

Permalink
Merge pull request #15 from Aanya9693/main
Browse files Browse the repository at this point in the history
Added Solution of Q31 of Leetcode in cpp
  • Loading branch information
DugarRishab authored Oct 2, 2022
2 parents 2a9fa1b + 645ba86 commit cd14fb7
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions leetCode Solutions/Q31_Next Permutation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
void nextPermutation(vector<int>& a) {
int idx=-1;

int n = a.size();
for(int i=n-1; i>0; i--){
if(a[i]>a[i-1]){
idx=i;
break;
}
}
if(idx == -1){ // if does not have a lexicographical larger rearrangement.
reverse(a.begin(), a.end());
}else{
int prev = idx;
for(int i=idx+1; i<n; i++){
if(a[i]>a[idx-1] and a[i]<=a[prev]){
prev=i;
}
}
swap(a[idx-1],a[prev]);
reverse(a.begin()+idx,a.end());
}
}
};

0 comments on commit cd14fb7

Please sign in to comment.