Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the stalls array in ascending order.
DSA Javascript
stalls.sort([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using (a, b) => b - a which sorts in descending order.
Not providing a comparator, which sorts numbers as strings.
✗ Incorrect
The sort function needs a comparator that sorts numbers in ascending order: (a, b) => a - b.
2fill in blank
mediumComplete the code to check if cows can be placed with at least 'distance' apart.
DSA Javascript
function canPlaceCows(stalls, cows, distance) {
let count = 1;
let lastPosition = stalls[0];
for (let i = 1; i < stalls.length; i++) {
if (stalls[i] - lastPosition >= [1]) {
count++;
lastPosition = stalls[i];
if (count === cows) return true;
}
}
return false;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with 'cows' or 'stalls.length' instead of 'distance'.
Using 'lastPosition' incorrectly in the comparison.
✗ Incorrect
We check if the gap between current stall and last placed cow is at least 'distance'.
3fill in blank
hardFix the error in the binary search loop condition to find the maximum minimum distance.
DSA Javascript
while (low <= [1]) { let mid = Math.floor((low + high) / 2); if (canPlaceCows(stalls, cows, mid)) { result = mid; low = mid + 1; } else { high = mid - 1; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mid' or 'result' in the loop condition which causes errors.
Using 'low <= low' which is always true and causes infinite loop.
✗ Incorrect
The binary search continues while low is less than or equal to high.
4fill in blank
hardFill both blanks to initialize the binary search boundaries correctly.
DSA Javascript
let low = [1]; let high = [2];
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting low to 1 instead of 0.
Setting high to stalls.length which is not a distance.
✗ Incorrect
Low starts at 0 (minimum distance), high is max possible distance between first and last stall.
5fill in blank
hardFill all three blanks to return the maximum minimum distance after binary search.
DSA Javascript
function aggressiveCows(stalls, cows) {
stalls.sort((a, b) => a - b);
let low = [1];
let high = [2];
let result = -1;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (canPlaceCows(stalls, cows, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return [3];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning high or low instead of result.
Setting low or high incorrectly.
✗ Incorrect
Low starts at 0, high is max distance, return the stored result after search.