Find next greater permutation

Given a number represented by a list of digits, find the next greater permutation of a number, in terms of lexicographic ordering. If there is not greater permutation possible, return the permutation with the lowest value/ordering.

For example, the list [1,2,3] should return [1,3,2]. The list [1,3,2] should return [2,1,3]. The list [3,2,1] should return [1,2,3].

Example:

Input:  nums[]={1,2,3}
Output: [1,3,2]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void nextPermutation(vector<int&nums)
{
    int index = -1;
    int n = nums.size();

    for (int i = n - 2; i >= 0; i--)
    {
        if (nums[i] < nums[i + 1])
        {
            index = i;
            break;
        }
    }
    if (index != -1)
    {
        for (int i = n - 1; i >= 0; i--)
        {
            if (nums[i] > nums[index])
            {
                swap(nums[i], nums[index]);
                break;
            }
        }
    }
    index++;
    int j = n - 1;

    while (index < j)
    {
        swap(nums[index], nums[j]);
        j--;
        index++;
    }

    return;
}

int main()
{
    vector<int> nums = {123};

    nextPermutation(nums);

    cout << "[";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i];
        if (i != nums.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment