Blog Archive

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

Example :

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.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Constraints:

1 ≤ N ≤ 100  

SOLUTION

vector<intnextPermutation(int nvector<intnums)
{
    // code here
    int idx = -1;
    for (int i = n - 1i > 0i--)
    {
        if (nums[i] > nums[i - 1])
        {
            idx = i;
            break;
        }
    }
    if (idx == -1)
    {
        reverse(nums.begin(), nums.end());
    }
    else
    {
        int prev = idx;
        for (int i = idx + 1i < ni++)
        {
            if (nums[i] > nums[idx - 1] && nums[i] <= nums[prev])
            {
                prev = i;
            }
        }
        swap(nums[idx - 1], nums[prev]);
        reverse(nums.begin() + idxnums.end());
    }
    return nums;
}

Data Structures & Algorithms, String and Array Data Structure


THANK  YOU...Explore Other Programmes Also

No comments:

Post a Comment

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...