Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Binary Search on Answer Technique in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Search on Answer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Binary Search on Answer for Minimum Maximum Subarray Sum
What is the output of the following TypeScript code that uses binary search on answer to find the minimum largest sum among subarrays?
DSA Typescript
function canSplit(nums: number[], maxSum: number, m: number): boolean {
  let currentSum = 0, count = 1;
  for (const num of nums) {
    if (num > maxSum) return false;
    if (currentSum + num > maxSum) {
      count++;
      currentSum = num;
      if (count > m) return false;
    } else {
      currentSum += num;
    }
  }
  return true;
}

function splitArray(nums: number[], m: number): number {
  let left = Math.max(...nums);
  let right = nums.reduce((a, b) => a + b, 0);
  while (left < right) {
    const mid = Math.floor((left + right) / 2);
    if (canSplit(nums, mid, m)) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }
  return left;
}

const nums = [7,2,5,10,8];
const m = 2;
console.log(splitArray(nums, m));
A18
B15
C20
D23
Attempts:
2 left
💡 Hint
Think about how the array can be split into 2 subarrays with minimum largest sum.
🧠 Conceptual
intermediate
1:30remaining
Understanding Binary Search on Answer Technique
Which of the following best describes the main idea behind the binary search on answer technique?
AUsing binary search to find the correct value in a sorted array directly.
BUsing binary search to find the index of a target value in a linked list.
CUsing binary search to sort an unsorted array efficiently.
DUsing binary search over a range of possible answers to find the minimum or maximum value that satisfies a condition.
Attempts:
2 left
💡 Hint
Think about searching over a range of values, not array indices.
🔧 Debug
advanced
2:30remaining
Identify the Bug in Binary Search on Answer Implementation
What is the bug in the following TypeScript code that tries to find the minimum maximum time to complete tasks by workers using binary search on answer?
DSA Typescript
function canComplete(tasks: number[], maxTime: number, workers: number): boolean {
  let currentTime = 0;
  let count = 1;
  for (const task of tasks) {
    if (task > maxTime) return false;
    if (currentTime + task > maxTime) {
      count++;
      currentTime = task;
      if (count > workers) return false;
    } else {
      currentTime += task;
    }
  }
  return true;
}

function minTime(tasks: number[], workers: number): number {
  let left = Math.max(...tasks);
  let right = tasks.reduce((a, b) => a + b, 0);
  while (left < right) {
    const mid = Math.floor((left + right) / 2);
    if (canComplete(tasks, mid, workers)) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }
  return left;
}

const tasks = [3, 6, 7, 11];
const workers = 2;
console.log(minTime(tasks, workers));
AThe mid calculation should use (left + right + 1) / 2 to avoid infinite loop.
BThe condition 'currentTime + task >= maxTime' should be 'currentTime + task > maxTime' to avoid extra worker count.
CThe function should return false if tasks array is empty.
DThe initial left boundary should be 0 instead of max task time.
Attempts:
2 left
💡 Hint
Check the condition that triggers a new worker assignment.
❓ Predict Output
advanced
2:00remaining
Output of Binary Search on Answer for Aggressive Cows Problem
What is the output of the following TypeScript code that uses binary search on answer to place cows in stalls maximizing minimum distance?
DSA Typescript
function canPlaceCows(stalls: number[], distance: number, cows: number): boolean {
  let count = 1;
  let lastPosition = stalls[0];
  for (let i = 1; i < stalls.length; i++) {
    if (stalls[i] - lastPosition >= distance) {
      count++;
      lastPosition = stalls[i];
      if (count >= cows) return true;
    }
  }
  return false;
}

function aggressiveCows(stalls: number[], cows: number): number {
  stalls.sort((a, b) => a - b);
  let left = 1;
  let right = stalls[stalls.length - 1] - stalls[0];
  let result = 0;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (canPlaceCows(stalls, mid, cows)) {
      result = mid;
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return result;
}

const stalls = [1, 2, 8, 4, 9];
const cows = 3;
console.log(aggressiveCows(stalls, cows));
A4
B5
C3
D6
Attempts:
2 left
💡 Hint
Think about placing cows with maximum minimum distance between them.
🧠 Conceptual
expert
1:30remaining
When to Use Binary Search on Answer Technique?
Which scenario is the best fit for applying binary search on answer technique?
AWhen the problem asks for an optimal numeric value that can be checked by a yes/no condition over a range.
BWhen you need to find an element in a sorted array by index.
CWhen you want to sort an array in O(n log n) time.
DWhen you need to traverse a tree in depth-first order.
Attempts:
2 left
💡 Hint
Think about searching over a range of possible answers with a feasibility check.

Practice

(1/5)
1. What is the main idea behind the Binary Search on Answer technique?
easy
A. We guess an answer and check if it satisfies the problem constraints, then adjust the guess.
B. We sort the input array before applying binary search.
C. We use binary search only on sorted arrays to find elements.
D. We divide the input into two halves and solve each recursively.

Solution

  1. Step 1: Understand the technique's purpose

    Binary Search on Answer guesses a possible answer value and checks if it meets the problem's conditions.
  2. Step 2: Adjust guess based on check

    If the guess is valid, we try smaller or larger values accordingly to find the optimal answer.
  3. Final Answer:

    We guess an answer and check if it satisfies the problem constraints, then adjust the guess. -> Option A
  4. Quick Check:

    Guess and check approach = C [OK]
Hint: Think of guessing answers and verifying them stepwise [OK]
Common Mistakes:
  • Confusing with normal binary search on arrays
  • Assuming input must be sorted
  • Thinking it divides input recursively
2. Which of the following is the correct TypeScript syntax to start a binary search on answer between low and high?
easy
A. while (low <= high) { let mid = (low + high) / 2; }
B. for (let mid = low; mid <= high; mid++) {}
C. while (low <= high) { let mid = Math.floor((low + high) / 2); }
D. if (low < high) { let mid = (low + high) >> 1; }

Solution

  1. Step 1: Identify correct mid calculation

    Midpoint must be an integer index, so use Math.floor to avoid decimals.
  2. Step 2: Confirm loop condition and syntax

    Use while loop with condition low <= high for binary search iteration.
  3. Final Answer:

    while (low <= high) { let mid = Math.floor((low + high) / 2); } -> Option C
  4. Quick Check:

    Integer mid with while loop = B [OK]
Hint: Use Math.floor for mid to avoid decimals in binary search [OK]
Common Mistakes:
  • Using division without floor causing float mid
  • Using for loop instead of while
  • Using bitwise shift without understanding
3. Consider this TypeScript code snippet using binary search on answer to find minimum capacity to ship packages within D days:
function canShip(weights: number[], capacity: number, D: number): boolean {
  let days = 1, total = 0;
  for (const w of weights) {
    if (total + w > capacity) {
      days++;
      total = 0;
    }
    total += w;
  }
  return days <= D;
}

function shipWithinDays(weights: number[], D: number): number {
  let low = Math.max(...weights);
  let high = weights.reduce((a, b) => a + b, 0);
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (canShip(weights, mid, D)) high = mid;
    else low = mid + 1;
  }
  return low;
}

console.log(shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5));
What is the output?
medium
A. 15
B. 10
C. 20
D. 5

Solution

  1. Step 1: Understand problem and code

    We find minimum ship capacity to ship weights in 5 days. Minimum capacity is max weight (10), max capacity is sum (55).
  2. Step 2: Trace binary search and canShip checks

    Binary search narrows capacity to 15, which allows shipping in 5 days by grouping weights properly.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Minimum capacity = 15 [OK]
Hint: Check max weight as low and sum as high for binary search [OK]
Common Mistakes:
  • Choosing max weight instead of sum as answer
  • Confusing days count in canShip function
  • Not using Math.floor for mid calculation
4. The following TypeScript code tries to find the maximum minimum distance between elements placed in positions array using binary search on answer. Identify the bug:
function canPlace(positions: number[], distance: number, m: number): boolean {
  let count = 1, lastPos = positions[0];
  for (let i = 1; i < positions.length; i++) {
    if (positions[i] - lastPos >= distance) {
      count++;
      lastPos = positions[i];
    }
  }
  return count >= m;
}

function maxMinDistance(positions: number[], m: number): number {
  positions.sort((a, b) => a - b);
  let low = 0, high = positions[positions.length - 1] - positions[0];
  while (low < high) {
    const mid = Math.floor((low + high + 1) / 2);
    if (canPlace(positions, mid, m)) low = mid;
    else high = mid - 1;
  }
  return low;
}
medium
A. Missing increment of count inside canPlace
B. Binary search mid calculation should not add 1
C. Binary search loop condition should be low <= high
D. No bug; code works correctly

Solution

  1. Step 1: Analyze canPlace function

    It correctly counts placements with given minimum distance.
  2. Step 2: Check binary search logic

    Mid uses upper mid to avoid infinite loop, loop condition low < high is valid, and updates low/high correctly.
  3. Final Answer:

    No bug; code works correctly -> Option D
  4. Quick Check:

    Code logic correct = A [OK]
Hint: Use upper mid to avoid infinite loop in binary search [OK]
Common Mistakes:
  • Changing loop condition incorrectly
  • Removing +1 in mid causing infinite loop
  • Forgetting to sort positions array
5. You want to find the minimum maximum time to complete all tasks by k workers, where each worker does continuous tasks. Given tasks array of times, how would you apply binary search on answer to solve this?
Choose the best approach.
hard
A. Calculate average time and assign tasks evenly without binary search.
B. Binary search on time range; check if tasks can be split into ≤ k groups with max sum ≤ mid.
C. Use binary search on number of tasks per worker directly.
D. Sort tasks and assign largest tasks first to workers.

Solution

  1. Step 1: Define search space for answer

    Minimum max time is max single task time; maximum is sum of all tasks.
  2. Step 2: Check feasibility with mid value

    Check if tasks can be divided into ≤ k continuous groups with max sum ≤ mid.
  3. Step 3: Adjust search space based on feasibility

    If feasible, try smaller max time; else increase it.
  4. Final Answer:

    Binary search on time range; check if tasks can be split into ≤ k groups with max sum ≤ mid. -> Option B
  5. Quick Check:

    Binary search on max time with group check = D [OK]
Hint: Binary search answer space, check feasibility with grouping [OK]
Common Mistakes:
  • Sorting tasks instead of binary searching answer
  • Trying to binary search on task count directly
  • Ignoring continuous group constraint
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard