0
0
DSA Typescriptprogramming~3 mins

Why Binary Search on Answer Technique in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find the perfect answer without trying every possibility?

The Scenario

Imagine you want to find the smallest size of a box that can fit all your items. You try sizes one by one, starting from the smallest. It takes forever and you get frustrated.

The Problem

Checking every possible size one by one is very slow and tiring. You might miss the best size or waste a lot of time trying sizes that are too small or too big.

The Solution

Binary Search on Answer Technique helps you guess the answer smartly. Instead of trying every size, you pick a middle size, check if it works, then decide to try bigger or smaller sizes. This way, you find the answer fast and without mistakes.

Before vs After
Before
let size = 1;
while (!canFit(size)) {
  size++;
}
return size;
After
let low = 1, high = maxSize;
while (low < high) {
  let mid = Math.floor((low + high) / 2);
  if (canFit(mid)) high = mid;
  else low = mid + 1;
}
return low;
What It Enables

This technique lets you quickly find the best answer in problems where the answer is a number and you can check if a guess is good or not.

Real Life Example

Finding the minimum time needed to complete all tasks when you can do multiple tasks at once, by guessing a time and checking if all tasks fit in it.

Key Takeaways

Manual checking is slow and error-prone.

Binary Search on Answer guesses answers smartly to save time.

It works when you can test if a guess is valid or not.