Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Binary Search on Answer Technique in DSA Javascript - 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 JavaScript code that uses binary search on answer to find the minimum largest sum among subarrays?
DSA Javascript
function canSplit(nums, maxSum, m) {
  let currentSum = 0, count = 1;
  for (const num of nums) {
    if (currentSum + num > maxSum) {
      count++;
      currentSum = num;
      if (count > m) return false;
    } else {
      currentSum += num;
    }
  }
  return true;
}

function splitArray(nums, m) {
  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 splitting the array into 2 parts such that the largest sum among them is minimized.
🧠 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?
APerform binary search on the input array elements directly to find a target value.
BUse binary search on a range of possible answers to find the minimum or maximum feasible value satisfying a condition.
CSort the array and then apply binary search to find the median element.
DUse binary search to find the first occurrence of a value in a sorted array.
Attempts:
2 left
💡 Hint
Think about searching over a range of values, not array indices.
🔧 Debug
advanced
2:00remaining
Identify the Error in Binary Search on Answer Implementation
What error does the following code produce when trying to find the minimum maximum subarray sum using binary search on answer?
DSA Javascript
function canSplit(nums, maxSum, m) {
  let currentSum = 0, count = 1;
  for (const num of nums) {
    if (currentSum + num >= maxSum) {
      count++;
      currentSum = num;
      if (count > m) return false;
    } else {
      currentSum += num;
    }
  }
  return true;
}

function splitArray(nums, m) {
  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));
AThe function does not handle empty arrays, causing runtime error.
BThe initial left boundary should be 0 instead of max element.
CThe condition 'currentSum + num >= maxSum' causes incorrect splitting, leading to wrong output.
DThe binary search loop condition should be 'left <= right' instead of 'left < right'.
Attempts:
2 left
💡 Hint
Check the condition that triggers a new subarray split.
🚀 Application
advanced
2:00remaining
Applying Binary Search on Answer to Allocate Books Problem
Given an array representing pages in books and number of students, which output is correct for minimum maximum pages allocated using binary search on answer?
DSA Javascript
function isPossible(books, maxPages, students) {
  let requiredStudents = 1, currentSum = 0;
  for (const pages of books) {
    if (pages > maxPages) return false;
    if (currentSum + pages > maxPages) {
      requiredStudents++;
      currentSum = pages;
      if (requiredStudents > students) return false;
    } else {
      currentSum += pages;
    }
  }
  return true;
}

function allocateBooks(books, students) {
  let left = Math.max(...books);
  let right = books.reduce((a, b) => a + b, 0);
  while (left < right) {
    const mid = Math.floor((left + right) / 2);
    if (isPossible(books, mid, students)) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }
  return left;
}

const books = [12, 34, 67, 90];
const students = 2;
console.log(allocateBooks(books, students));
A113
B157
C67
D90
Attempts:
2 left
💡 Hint
Try splitting books into 2 students with minimum maximum pages.
🧠 Conceptual
expert
1:30remaining
Why is Binary Search on Answer Efficient for Certain Problems?
Why does binary search on answer technique provide an efficient solution for problems like splitting arrays or allocating resources?
ABecause it uses dynamic programming to store intermediate results.
BBecause it sorts the input data first, reducing complexity.
CBecause it uses recursion to explore all possible partitions quickly.
DBecause it converts a complex problem into a series of feasibility checks over a numeric range, reducing search space logarithmically.
Attempts:
2 left
💡 Hint
Think about how the search space is reduced step by step.

Practice

(1/5)
1. What is the main idea behind the Binary Search on Answer technique?
easy
A. We guess an answer and use binary search to find the smallest or largest valid value.
B. We sort the array and then apply binary search to find an element.
C. We use binary search to find the middle element in a sorted list.
D. We apply binary search to split the array into two halves repeatedly.

Solution

  1. Step 1: Understand the technique's goal

    Binary Search on Answer guesses a possible answer and checks if it meets the problem's conditions.
  2. Step 2: Use binary search on the answer range

    We narrow down the answer by checking mid-values until we find the smallest or largest valid answer.
  3. Final Answer:

    We guess an answer and use binary search to find the smallest or largest valid value. -> Option A
  4. Quick Check:

    Binary Search on Answer = Guess and check with binary search [OK]
Hint: Think of binary searching the answer, not the array [OK]
Common Mistakes:
  • Confusing it with normal binary search on sorted arrays
  • Trying to binary search elements instead of answer values
  • Not defining a valid check function for guesses
2. Which of the following is the correct syntax to start a binary search on answer in JavaScript for a range from low to high?
easy
A. for (let mid = low; mid <= high; mid++) { }
B. while (low <= high) { let mid = Math.floor((low + high) / 2); }
C. if (low < high) { mid = (low + high) / 2; }
D. do { mid = (low + high) / 2; } while (low < high);

Solution

  1. Step 1: Identify the binary search loop structure

    Binary search uses a while loop checking low <= high to continue searching.
  2. Step 2: Calculate mid correctly

    Mid is calculated as Math.floor((low + high) / 2) to get the middle integer index.
  3. Final Answer:

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

    Correct binary search loop syntax = while (low <= high) { let mid = Math.floor((low + high) / 2); } [OK]
Hint: Use while loop with low <= high and floor mid [OK]
Common Mistakes:
  • Using for loop instead of while for binary search
  • Not flooring mid value causing float indices
  • Using incorrect loop conditions like low < high
3. Consider the following code snippet using binary search on answer to find the minimum capacity to ship packages within D days:
function canShip(weights, capacity, D) {
  let days = 1, currentLoad = 0;
  for (let w of weights) {
    if (currentLoad + w > capacity) {
      days++;
      currentLoad = 0;
    }
    currentLoad += w;
  }
  return days <= D;
}

function shipWithinDays(weights, D) {
  let low = Math.max(...weights);
  let high = weights.reduce((a, b) => a + b, 0);
  while (low < high) {
    let 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 of this code?
medium
A. 20
B. 10
C. 15
D. 5

Solution

  1. Step 1: Understand the problem and code

    The code finds the minimum ship capacity to ship weights in 5 days. It uses binary search between max weight (10) and sum (55).
  2. Step 2: Trace binary search narrowing

    Checking mid values, the minimum capacity that allows shipping in 5 days is 15.
  3. Final Answer:

    15 -> Option C
  4. Quick Check:

    Minimum capacity to ship in 5 days = 15 [OK]
Hint: Check max weight and sum, binary search between them [OK]
Common Mistakes:
  • Choosing max weight (10) as answer instead of minimum capacity
  • Choosing total sum (55) instead of minimum valid capacity
  • Misunderstanding the days condition in canShip
4. The following code tries to find the maximum length of a rope to cut at least k pieces using binary search on answer. Find the bug:
function maxLength(ropes, k) {
  let low = 0;
  let high = Math.max(...ropes);
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    let count = 0;
    for (let r of ropes) {
      count += Math.floor(r / mid);
    }
    if (count >= k) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return high;
}
medium
A. Using while (low <= high) instead of while (low < high) is wrong.
B. Not sorting ropes before binary search causes wrong answer.
C. Returning high instead of low is incorrect.
D. Starting low from 0 causes division by zero error.

Solution

  1. Step 1: Identify potential division by zero

    Starting low at 0 means mid can be 0, causing division by zero in Math.floor(r / mid).
  2. Step 2: Fix low initialization

    Set low to 1 to avoid division by zero and ensure valid rope length guesses.
  3. Final Answer:

    Starting low from 0 causes division by zero error. -> Option D
  4. Quick Check:

    low = 0 causes divide by zero [OK]
Hint: Avoid zero as divisor in binary search on answer [OK]
Common Mistakes:
  • Ignoring division by zero possibility
  • Changing loop condition unnecessarily
  • Returning wrong boundary without reason
5. You want to find the minimum maximum time to complete all tasks by k workers, where each worker can do consecutive tasks only. Given task times array tasks, how would you apply binary search on answer to solve this?

Choose the best approach:
hard
A. Binary search on time range; check if tasks can be split into ≤ k groups with max sum ≤ mid.
B. Sort tasks and binary search for the smallest task time.
C. Use binary search on number of tasks each worker gets, ignoring task times.
D. Apply binary search on total tasks count to assign tasks evenly.

Solution

  1. Step 1: Define the answer range

    The minimum max time is at least max task time, max is sum of all tasks.
  2. Step 2: Check feasibility with mid value

    Check if tasks can be split into ≤ k groups where each group's sum ≤ mid.
  3. Step 3: Use binary search to narrow answer

    Adjust low and high based on feasibility until minimum max time is found.
  4. Final Answer:

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

    Binary search on max time with group feasibility check [OK]
Hint: Binary search answer range, check group splits feasibility [OK]
Common Mistakes:
  • Binary searching on tasks count instead of time
  • Ignoring consecutive task grouping constraint
  • Sorting tasks unnecessarily
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