Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the next permutation by swapping the pivot with the right element.
DSA C++
int i = nums.size() - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } if (i >= 0) { int j = nums.size() - 1; while (j >= 0 && nums[j] <= nums[i]) { j--; } std::swap(nums[i], nums[[1]]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with i or i+1 instead of j.
Not finding the correct j index.
✗ Incorrect
We swap the element at index i (pivot) with the element at index j, which is the first element from the right greater than nums[i].
2fill in blank
mediumComplete the code to reverse the suffix of the array after the pivot index.
DSA C++
int start = i + 1; int end = nums.size() - 1; while (start < [1]) { std::swap(nums[start], nums[end]); start++; end--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using start instead of end in the condition.
Looping until start <= end causing extra swaps.
✗ Incorrect
We reverse the suffix by swapping elements from start to end until start meets end.
3fill in blank
hardFix the error in the loop that finds the pivot index where the next permutation changes.
DSA C++
int i = nums.size() - 2; while (i >= 0 && nums[i] [1] nums[i + 1]) { i--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' causing wrong pivot detection.
Using '<=' or '>' which do not find the correct pivot.
✗ Incorrect
We move left while nums[i] is greater than or equal to nums[i+1] to find the pivot where the order breaks.
4fill in blank
hardFill both blanks to correctly find the next permutation by swapping and reversing the suffix.
DSA C++
if (i >= 0) { int j = nums.size() - 1; while (j >= 0 && nums[j] [1] nums[i]) { j--; } std::swap(nums[i], nums[[2]]); } int start = i + 1; int end = nums.size() - 1; while (start < end) { std::swap(nums[start], nums[end]); start++; end--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the while condition.
Swapping with i instead of j.
✗ Incorrect
We find j where nums[j] is greater than nums[i], then swap nums[i] and nums[j].
5fill in blank
hardFill all three blanks to implement the next permutation function correctly.
DSA C++
void nextPermutation(std::vector<int>& nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i] [1] nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.size() - 1;
while (j >= 0 && nums[j] [2] nums[i]) {
j--;
}
std::swap(nums[i], nums[[3]]);
}
int start = i + 1;
int end = nums.size() - 1;
while (start < end) {
std::swap(nums[start], nums[end]);
start++;
end--;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators in loops.
Swapping with wrong index.
✗ Incorrect
The pivot is found by moving left while nums[i] >= nums[i+1]. Then j moves left while nums[j] <= nums[i]. Finally, swap nums[i] and nums[j].
