0
0
DSA Goprogramming~3 mins

Why Binary Search on Answer Technique in DSA Go?

Choose your learning style9 modes available
The Big Idea

What if you could find the perfect answer by guessing smartly instead of trying everything?

The Scenario

Imagine you want to find the smallest size of a box that can hold all your items, but you only know the total number of items and their sizes. You try different box sizes one by one, measuring if all items fit. This takes forever and is very tiring.

The Problem

Trying every possible box size manually is slow and frustrating. You waste time checking sizes that are obviously too small or too big. It's easy to make mistakes and lose track of which sizes you already tested.

The Solution

The Binary Search on Answer technique helps by smartly guessing the box size. It checks the middle size first, then decides if it should try bigger or smaller sizes next. This way, it quickly narrows down to the perfect size without testing every option.

Before vs After
Before
for size := minSize; size <= maxSize; size++ {
    if canFitAllItems(size) {
        return size
    }
}
After
low, high := minSize, maxSize
for low <= high {
    mid := (low + high) / 2
    if canFitAllItems(mid) {
        high = mid - 1
    } else {
        low = mid + 1
    }
}
return low
What It Enables

This technique makes it possible to solve complex problems by guessing answers efficiently, saving time and effort.

Real Life Example

Suppose you want to split a long video into parts of equal length so that each part fits on a DVD. Binary Search on Answer helps find the smallest maximum length per part quickly.

Key Takeaways

Manual checking of all answers is slow and error-prone.

Binary Search on Answer guesses smartly to find the correct answer fast.

It is useful when the answer lies within a range and can be tested quickly.