Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the stalls array.
DSA Typescript
stalls.sort((a, b) => a [1] b); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '-' causes descending order.
Using '-' directly without a function returns NaN.
✗ Incorrect
The sort function needs a comparison that returns a negative value when a is less than b, so using '-' in the comparison function is correct.
2fill in blank
mediumComplete the code to check if cows can be placed with at least mid distance.
DSA Typescript
if (stalls[i] - lastPos [1] mid) {
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' places cows too close.
Using '==' is too strict and misses valid placements.
✗ Incorrect
We want to place a cow only if the distance between current stall and last placed cow is at least mid, so '>=' is correct.
3fill in blank
hardFix the error in the binary search loop condition.
DSA Typescript
while (low [1] high) {
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' misses checking when low equals high.
Using '>' or '>=' reverses the logic.
✗ Incorrect
The binary search continues while low is less than or equal to high to cover all possible distances.
4fill in blank
hardFill both blanks to update the binary search bounds correctly.
DSA Typescript
if (canPlaceCows(stalls, cows, mid)) { result = mid; low = mid [1] 1; } else { high = mid [2] 1; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping '+' and '-' causes infinite loops.
Using '*' or '/' is incorrect for adjusting bounds.
✗ Incorrect
If cows can be placed, we try for a bigger distance by increasing low. Otherwise, we decrease high to try smaller distances.
5fill in blank
hardFill the blanks to complete the canPlaceCows function logic.
DSA Typescript
function canPlaceCows(stalls: number[], cows: number, mid: number): boolean {
let count = 1;
let lastPos = stalls[0];
for (let i = 1; i < stalls.length; i++) {
if (stalls[i] - lastPos [1] mid) {
count++;
lastPos = stalls[i];
if (count [2] cows) {
return true;
}
}
}
return false;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' for distance check is too strict.
Using '<=' for count comparison is incorrect.
✗ Incorrect
We check if distance is at least mid (>=), increment count, and if count is greater than or equal to cows, return true. The lastPos update is already in code.