MCPcopy Create free account
hub / github.com/Vishruth-S/CompetitiveCode / Solution

Class Solution

LeetCode_problems/Next Permutation/solution.cpp:2–34  ·  view source on GitHub ↗

time complexity -O(n),space complexity -O(1)*/

Source from the content-addressed store, hash-verified

1/*time complexity -O(n),space complexity -O(1)*/
2class Solution {
3public:
4 void nextPermutation(vector<int>& nums) {
5 int n=nums.size();
6 int j=n-1;
7 /*starting from the right side check upto which
8 index the array is non-decreasing*/
9
10 while(j!=0&&nums[j]<=nums[j-1])
11 j--;
12 /* the array is in descending order which represents
13 the maximum possible lexicographical permutation*/
14 if(j==0)
15 {
16 reverse(nums.begin(),nums.end());
17 return;
18 }
19 j--;
20 /*nums[j] will be swapped with the smallest number
21 greater than nums[j] on the right side*/
22 for(int i=n-1;i>j;i--)
23 {
24 if(nums[i]>nums[j])
25 {
26 swap(nums[i],nums[j]);
27 /* new nums[j] has greater value so, sort or just
28 reverse the array from j+1 th index to last*/
29 reverse(nums.begin()+j+1,nums.end());
30 return;
31 }
32 }
33 }
34};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected