0
0
DSA Javascriptprogramming~10 mins

Aggressive Cows Maximum Minimum Distance in DSA Javascript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A() => 1
B() => 0
C(a, b) => b - a
D(a, b) => a - b
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.
2fill in blank
medium

Complete 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'
Adistance
Bcows
Cstalls.length
DlastPosition
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with 'cows' or 'stalls.length' instead of 'distance'.
Using 'lastPosition' incorrectly in the comparison.
3fill in blank
hard

Fix 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'
Amid
Blow
Chigh
Dresult
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.
4fill in blank
hard

Fill 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'
A1
B0
Cstalls[stalls.length - 1] - stalls[0]
Dstalls.length
Attempts:
3 left
💡 Hint
Common Mistakes
Setting low to 1 instead of 0.
Setting high to stalls.length which is not a distance.
5fill in blank
hard

Fill 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'
A0
Bstalls.length - 1
Cresult
Dstalls[stalls.length - 1] - stalls[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Returning high or low instead of result.
Setting low or high incorrectly.