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<int> nextPermutation(int n, vector<int> nums)
{
// code here
int idx = -1;
for (int i = n - 1; i > 0; i--)
{
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 + 1; i < n; i++)
{
if (nums[i] > nums[idx - 1] && nums[i] <= nums[prev])
{
prev = i;
}
}
swap(nums[idx - 1], nums[prev]);
reverse(nums.begin() + idx, nums.end());
}
return nums;
}
THANK YOU...Explore Other Programmes Also