Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the first index from the end where the array value is smaller than the next value.
DSA Javascript
let i = nums.length - 2; while (i >= 0 && nums[i] [1]= nums[i + 1]) { i--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '>=' causes missing equal elements.
Using '<' or '<=' reverses the logic.
✗ Incorrect
We look for the first index from the right where nums[i] is less than nums[i+1], so we continue while nums[i] >= nums[i+1].
2fill in blank
mediumComplete the code to find the first index from the end where the array value is greater than nums[i].
DSA Javascript
if (i >= 0) { let j = nums.length - 1; while (nums[j] [1]= nums[i]) { j--; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '>' reverses the logic.
Using '<' instead of '<=' causes picking equal elements.
✗ Incorrect
We want to find the first element from the right that is greater than nums[i], so we continue while nums[j] <= nums[i].
3fill in blank
hardFix the error in swapping nums[i] and nums[j].
DSA Javascript
let temp = nums[i]; nums[i] = nums[[1]]; nums[[1]] = temp;
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with the wrong index causes incorrect permutation.
Using i instead of j for the second index.
✗ Incorrect
We swap nums[i] with nums[j], so both places must use j for the second index.
4fill in blank
hardFill both blanks to reverse the subarray after index i.
DSA Javascript
let start = i + 1; let end = nums.length - 1; while (start [1] end) { let temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start[2]; end--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes swapping the same element twice.
Using '--' on start moves it backward incorrectly.
✗ Incorrect
We reverse the subarray by swapping while start < end, incrementing start and decrementing end.
5fill in blank
hardFill all three blanks to complete the next permutation function.
DSA Javascript
function nextPermutation(nums) {
let i = nums.length - 2;
while (i >= 0 && nums[i] [1]= nums[i + 1]) {
i--;
}
if (i >= 0) {
let j = nums.length - 1;
while (nums[j] [2]= nums[i]) {
j--;
}
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
let start = i + 1;
let end = nums.length - 1;
while (start [3] end) {
let temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up comparison operators causes wrong permutations.
Using '<=' in the reversal loop causes extra swaps.
✗ Incorrect
The first while uses '>=' to find the pivot, the second uses '<=' to find the swap candidate, and the last uses '<' to reverse the suffix.
