VV easy C++ solution


#1

To understand logic check InterviewBit’s problem discussion on the same name on Youtube.

vector<int> Solution::nextPermutation(vector<int> &A) {
int N = A.size();
int x = -1;
for (int i=N-2; i>=0; i--) {
    if (A[i] < A[i+1]) {
        x = i;
        break;
    }
}
if (x == -1) {
    sort(A.begin(), A.end());
} else if (x + 1 < N){
    sort(A.begin() + x + 1, A.end());
    for (int i=x+1; i<N; i++) {
        if (A[i] > A[x]) {
            //int tmp = A[i];
            //A[i] = A[x];
            //A[x] = tmp;
            swap(A[i], A[x]);
            break;
        }
    }
}
return A;
}

#2

Hi Hari, You can just reverse the array instead of using STL’s Sort() api, this will improve your time complexity from O(nlogn) to O(n).