Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the next permutation by swapping the right elements.
DSA Java
int i = nums.length - 2; while (i >= 0 && nums[i] >= nums[i + [1]]) { i--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using nums[i + 2] instead of nums[i + 1]
Using >= incorrectly causing infinite loop
Starting i from 0 instead of nums.length - 2
✗ Incorrect
We compare nums[i] with nums[i + 1] to find the first decreasing element from the right.
2fill in blank
mediumComplete the code to find the element to swap with nums[i].
DSA Java
int j = nums.length - 1; while (j >= 0 && nums[j] <= nums[[1]]) { j--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing nums[j] with nums[j]
Using wrong index instead of i
Not decrementing j properly
✗ Incorrect
We find the first element from the right that is greater than nums[i].
3fill in blank
hardFix the error in swapping elements nums[i] and nums[j].
DSA Java
int temp = nums[[1]];
nums[i] = nums[j];
nums[j] = temp;Attempts:
3 left
💡 Hint
Common Mistakes
Using nums[j] in temp causing wrong swap
Swapping without temp causing data loss
Using wrong indices
✗ Incorrect
We store nums[i] in temp before swapping with nums[j].
4fill in blank
hardFill both blanks to reverse the suffix of the array after index i.
DSA Java
int start = i + [1]; int end = nums.length - 1; while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting reversal at i instead of i + 1
Using wrong start index causing incorrect reversal
Not reversing suffix fully
✗ Incorrect
We start reversing from the element right after i, so start = i + 1.
5fill in blank
hardFill all three blanks to complete the next permutation method.
DSA Java
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + [1]]) {
i--;
}
if (i >= 0) {
int j = nums.length - 1;
while (j >= 0 && nums[j] <= nums[[2]]) {
j--;
}
int temp = nums[[3]];
nums[[3]] = nums[j];
nums[j] = temp;
}
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices causing incorrect swaps
Not checking i >= 0 before swapping
Mixing up i and j in swaps
✗ Incorrect
The blanks correspond to: i + 1 for the first loop, nums[i] for comparison, and nums[i] for swapping.
