What if you could find the perfect answer without trying every possibility?
Why Binary Search on Answer Technique in DSA Typescript?
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.
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.
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.
let size = 1; while (!canFit(size)) { size++; } return size;
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;
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.
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.
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.