Ninja technique🥷 to ACE DSA Interviews.
next_permutation(a.being(),a.end())
function in c++.class Solution {
public:
void nextPermutation(vector<int>& nums){
next_permutation(nums.begin(), nums.end());
}
};
k
such that nums[k] < nums[k + 1]
. If no such index exists, just reverse nums
and done.
2.From back find the largest index l > k
such that nums[k] < nums[l]
. 3.Swap
nums[k]
and nums[l]
. 4.Reverse
the sub-array nums[k + 1:]
.class Solution {
public:
void nextPermutation(vector<int>& nums)
{
int n = nums.size(), k, l;
for (k = n - 2; k >= 0; k--) { // Step 1
if (nums[k] < nums[k + 1]) {
break;
}
}
if (k < 0) {
reverse(nums.begin(), nums.end());
} else {
for (l = n - 1; l > k; l--) { // Step 2
if (nums[l] > nums[k]) {
break;
}
}
swap(nums[k], nums[l]); //Step 3
reverse(nums.begin() + k + 1, nums.end()); //Step 4
}
}
};