Next Permutation | Practice | GeeksforGeeks

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.
Example 1:
Input: N = 6
arr = {1, 2, 3, 6, 5, 4}
Output: {1, 2, 4, 3, 5, 6}
Explaination: The next permutation of the 
given array is {1, 2, 4, 3, 5, 6}.
Example 2:
Input: N = 3
arr = {3, 2, 1}
Output: {1, 2, 3}
Explaination: As arr[] is the last 
permutation. So, the next permutation 
is the lowest one.
Your Task:
You do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10000
0
antaryamisingh2521 day ago
vector<int> nextPermutation(int N, vector<int> arr){       int i =0;    for(i = N-1; i>0; i--)    {    if(arr[i-1] < arr[i]){        sort(arr.begin()+i, arr.end());                for(int j=i; j<N; j++){            if(arr[i-1] < arr[j]){                swap(arr[i-1], arr[j]);                break;            }        }        break;    }          }    if(i==0){        sort(arr.begin(), arr.end());    }    return arr; }
0
hasnainansari97576 days ago
class Solution{
public:
    vector<int> nextPermutation(int N, vector<int> arr){
        // code here
        vector<int> ans;
        int idx = -1;
        for(int i=N-1;i>0;i--){
            if(arr[i] > arr[i-1]){ 
                idx = i; 
                break;
            }
        }
       
        if(idx == -1){ 
            reverse(arr.begin(), arr.end());
        }
        else{
            int prev = idx;
            for(int i=idx+1;i<N;i++){ 
                if(arr[i] > arr[idx-1] && arr[i] <= arr[prev]){
                    prev = i;
                }
            }
            swap(arr[idx-1], arr[prev]);
            reverse(arr.begin()+idx, arr.end());
           
           
        }
       
        for(int i=0;i<N;i++){
            ans.push_back(arr[i]);
        }
        return ans;
       
       
    }
};
0
vermaanshu20051 week ago
Java 0.17/1.14




class Solution{
    static List<Integer> nextPermutation(int n, int arr[]){
        List<Integer> list = new ArrayList<>();
        int i = n-2;
        int ind1 = -1;
        while(i >= 0)
        {
            if(arr[i] < arr[i+1])
            {
                ind1 = i;
                break;
            }
            i--;
        }
        
        if(ind1 == -1)
        {
            reverse(arr, 0);
            makeList(list, arr);
            return list; 
        }
        i = n-1;
        int ind2 = -1;
        while(i >= 0)
        {
            if(arr[i] > arr[ind1])
            {
                ind2 = i;
                break;
            }
            i--;
        }
        
        swap(arr, ind1, ind2);
        
        reverse(arr, ind1 + 1);
        makeList(list, arr);
        return list; 
    }
    
    static void swap(int arr[], int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    static void reverse(int arr[], int index)
    {
        int i = index;
        int j = arr.length - 1;
        while(i < j)
        {
            swap(arr, i, j);
            i++;
            j--;
        }
    }
    
    static void makeList(List<Integer> list, int arr[])
    {
        for(int i=0;i<arr.length;i++)
        {
            list.add(arr[i]);
        }
    }
}
+1
sparshtanejaa1 week ago
best solution you will find so far 0.01ms time
 
 vector<int> nextPermutation(int N, vector<int> s){       // code here       next_permutation(s.begin(),s.end());       return s;       }
-1
hoodninja3 weeks ago
        int i,j;
        i = n-2;
        
        
        while(arr[i] >= arr[i+1] && i>=0)
        {
            i--;
        }
       
        if(i==-1)
        {
            reverse(arr.begin(),arr.end());
            return arr;
        }
        j = n-1;
        while(arr[j]<arr[i])
        {
            j--;
        }
        swap(arr[i],arr[j]);
        
        reverse(arr.begin() + i + 1,arr.end());
        return arr;
0
abhitheagrawal3 weeks ago
vector<int> nextPermutation(int N, vector<int> arr){             bool val = next_permutation(arr.begin(),arr.end());       if(val==false)       {           sort(arr.begin(),arr.end());          return arr;;       }        return arr;       // code here   }
0
ritikyadavr113 weeks ago
class Solution{public:   vector<int> nextPermutation(int N, vector<int> arr){       // find pivote element or largest non increasing suffix       int l,r;       for(l=N-2; l>=0; l--) {           if(arr[l] < arr[l+1]) break;       }       if(l < 0) reverse(arr.begin(),arr.end());       else{           //find right most successor to pivote in suffix           for(r=N-1; r>l; r--) {               if(arr[r]>arr[l]) break;           }           //swap l,r           swap(arr[l],arr[r]);           //reverse l+1 to end           reverse(arr.begin()+l+1,arr.end());       }       return arr;   }}; 
+1
amishasahu3283 weeks ago
class Solution{
public:
    vector<int> nextPermutation(int N, vector<int> arr){
        // code here
        int x = -1, y = -1;
        for(int i = 0; i < N-1; i++)
            if(arr[i] < arr[i+1])
                x = i;
        
        if(x == -1)
        {
            sort(arr.begin(), arr.end());
            return arr;
        }
        
        for(int i = x+1; i < N; i++)
        {
            if(arr[x] < arr[i])
                y = i;
        }
        
        swap(arr[x], arr[y]);
        
        reverse(arr.begin()+x+1, arr.end());
        return arr;
    }
};
0
rs263 weeks ago
JAVA Sol.
Time -: 0.2/1.1 sec
class Solution{
    static List<Integer> nextPermutation(int N, int arr[]){
        // code here
        ArrayList<Integer> a1=new ArrayList<>();
            ArrayList<Integer> a2=new ArrayList<>();
        int max_ind=Integer.MIN_VALUE;
        int c=0;
        for(int i=0;i<N-1;i++)
        {
           if(arr[i]<arr[i+1] && max_ind<i) 
           max_ind=i;
        }
        if(max_ind<0)
        {
        Arrays.sort(arr);
        for(int i=0;i<N;i++)
        a1.add(arr[i]);
        }
        else
        {
            int max=-1;
            for(int i=max_ind+1;i<N;i++)
            {
                if(arr[max_ind]<arr[i] && max<i)
                max=i;
            }
            int temp=arr[max_ind];
            arr[max_ind]=arr[max];
            arr[max]=temp;
            
            for(int i=0;i<=max_ind;i++)
            {
                a1.add(arr[i]);
            }
            for(int i=N-1;i>max_ind;i--)
            {
                a2.add(arr[i]);
            }
            a1.addAll(a2);
        }
        return a1;
    }
}
+1
bhargabnath6913 weeks ago
Time Taken: 0.0/1.1
Approach: Find the first dip element from end of the array.
If there is no such dip element, it simply means that the given array is in descending order, hence reverse the array and return it.
Otherwise, look for the first element which is greater than the dip, and then swap the dip and peak element. Till this point we have observed the dip and peak element from the end of the array and we also swapped them between themselves, thus earlier dip is now peak and earlier peak is now dip. But the twist here is that, between these 2 elements,  the elements should also be in ascending order, so we have got to reverse the array right from the next element to the index of the earlier dip(or new peak) element.  That will be the final array for us.
 
For example: [2, 4, 1, 5, 3]
First dip element from the end of the array: 1 (NOTE: we keep track of dip element's index here, not the dip element itself , similarly for peak element also)
So, dip = 2(index of the dip element)
 
Then, first peak element from the end of the array which is greater than dip element = 3
So, peak =  4 (index of the peak element)
 
swap(nums[dip], nums[peak]) = swap(nums[2], nums[4]) = swap(1, 3)
The array now is: [2, 4, 3, 5, 1],
But it's not our final answer, since we can easily observe from here, that, [2, 4, 3, 1, 5] is an array which is lexicographically smaller than [2, 4, 3, 5, 1]
So, we need to have the elements after dip(index, not to forget, which is 2 here) in ascending order, therefore, reverse the array from the dip + 1 to end index and that is the final output array for us.
So, reverse(arr.begin() + dip + 1, arr.end()) = reverse(0+2+1, 4) = reverse(3, 4)
Thus, [2,4,3,1,5] = final answer, return it.
 
	vector<int> nextPermutation(int N, vector<int> arr){
        // code here
        int peak;
        int dip;
        for(dip=N-2; dip>=0; dip--){
            if(arr[dip] < arr[dip+1]) break;
        }
        if(dip < 0) reverse(arr.begin(), arr.end());
        else {
            for(peak=N-1; peak>dip; peak--){
                if(arr[peak] > arr[dip]) break;
            }
            swap(arr[peak], arr[dip]);
            reverse(arr.begin() + dip + 1, arr.end());
        }
        return arr;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.