Skip to main content

Stop Thinking Binary Search Is Only for Searching πŸ”

It’s a way of asking the right questions and making the right choice.

Updated 7 min readMarkdown
Stop Thinking Binary Search Is Only for Searching πŸ”

It’s not an algorithm to memorize. Most of us learn binary search like this: β€œSorted array. Find the target. Done.”

But the real skill is spotting when it fits, even when the problem has no sorted array at all.

Ask the problem 3 questions:

❓ Is there an order in which my answer lies? Is my data range sorted, or can I treat it as ordered (small β†’ big)?

❓ Does my answer live in that fixed range? Is it always between a min and a max?

❓ What kind of problem is it?

Type 1: Find the answer inside the data range given. Example: find the position of a number in a sorted array.

Type 2: Guess an answer and test it against a range value. Example: Koko must eat all banana piles within a given number of hours. What is the slowest eating speed that works?

Now make an assumption 🎯

Say my answer is exactly in the middle. After checking, I have only 3 choices:

  1. The middle is the answer βœ… I found it. Stop.

  2. The middle is smaller than what I need ⬅️ Everything at or below the middle cannot be my answer. πŸ‘‰ Ignore that part. Look at the right half.

  3. The middle is bigger than what I need ➑️ Everything at or above the middle cannot be my answer. πŸ‘‰ Ignore that part. Look at the left half.

Repeat: assume β†’ check β†’ ignore one side.

Stop when no data is left to check. If you never found a match, the answer is not there.

So idea πŸ’‘

Binary search is just this: Make one smart guess in the middle. Check it. Safely throw away half. Every round, the problem gets half as big.

Example: Capacity To Ship Packages Within D Days
Link: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

A conveyor belt has packages with weights. A ship must carry all of them within D days. Packages must go in the given order. You cannot reorder them. Each day, you load packages onto the ship in order, but the total weight cannot go over the ship’s capacity. Find the smallest capacity that finishes all packages within D days.

Input: weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] D = 5

Output : 15

Now let's solve this problem using the above discussed process.

Solution:

Step 0: Ask the problem the questions

  • ❓ Is there an order? The answer is a capacity (a number). Bigger capacity=smaller days and small capacity=more days. So small β†’ big capacities behave in order. Yes.

  • ❓ Is the answer in a fixed range? Yes. the lowest capacity it will have is (highest of the weights) and highest capacity will be (sum of all the weights)

  • ❓ Find it in the data, or guess and test? The answer is not inside the weights list. We guess a capacity and test it. Type 2.

Finding the range:

  • Smallest possible = 10. The ship must at least carry the heaviest package. Anything less cannot carry it at all.

  • Biggest possible = 55. That is the sum of all weights. The ship carries everything in 1 day. A bigger ship is useless.

Capacity:  10 ............................................ 55
           ^ heaviest package                    all packages ^
           (min)                                  in one day (max)

The yes/no test (we repeat this every round)

β€œIf the ship’s capacity is X, can I finish in 5 days or less?”

test: load packages in order. When the next package does not fit, start a new day. Count the days.

  • Days ≀ 5 β†’ YES. This capacity works, it may be our answer(save it). but we want a smaller one if that works too, so ignore the bigger side.

  • Days > 5 β†’ NO. The ship is too small. Ignore the smaller side.

Solving step by step

Round 1: range 10 to 55 | Middle = (10 + 55) Γ· 2 β‰ˆ 32

Test capacity 32:

Day 1: 1+2+3+4+5+6+7 = 28   (adding 8 β†’ 36, too much)
Day 2: 8+9+10        = 27  2 days. 2 ≀ 5, so YES βœ…
Decision: 32 works, but a smaller one may work too. Ignore everything above 32.

Round 2: range 10 to 32 | Middle = 21

  • Test capacity 21:
Day 1: 1+2+3+4+5+6 = 21
Day 2: 7+8         = 15   (adding 9 β†’ 24, too much)
Day 3: 9+10        = 19      3 days. YES βœ…
Decision: Ignore everything above 21.(we want smallest)

Round 3: range 10 to 21 | Middle = 15

  • Test capacity 15:
Day 1: 1+2+3+4+5 = 15
Day 2: 6+7       = 13
Day 3: 8         = 8     (adding 9 β†’ 17, too much)
Day 4: 9         = 9     (adding 10 β†’ 19, too much)
Day 5: 10        = 10     5 days. 5 ≀ 5, so YES βœ…
Decision: Ignore everything above 15.

Round 4: range 10 to 15 | Middle = 12

  • Test capacity 12:
Day 1: 1+2+3+4 = 10
Day 2: 5+6     = 11
Day 3: 7       = 7
Day 4: 8       = 8
Day 5: 9       = 9
Day 6: 10      = 10   6 days. 6 > 5, so NO ❌
Decision: 12 is too small, so 10, 11 and 12 are all too small. Ignore everything up to 12.

Round 5: range 13 to 15 | Middle = 14

the total days will be 6 , which is >5 so will shift to higher side, and only one left : 15

we have already tested it. so the range finishes here and the answer is 15.

Capacity: 10  11  12  13  14 | 15  16 ... 32 ... 55
           ❌  ❌  ❌  ❌  ❌ |  βœ…  βœ…     βœ…      βœ…
                              ^
                  smallest capacity that works

Answer: 15 πŸŽ‰

What to notice

  • Only 5 tests instead of trying all 46 capacities from 10 to 55.

  • Every test is the same yes/no question, and every answer let us throw away a big part of the range.

  • This works because of one rule: bigger capacity never needs more days. If this rule did not hold, we could not throw anything away.

Search these names on Google or LeetCode.

Type 1: find it inside the data

  • Binary Search (the basic one)

  • Search Insert Position

  • First and Last Position of an Element in a Sorted Array

  • Search in Rotated Sorted Array

  • Find Minimum in Rotated Sorted Array

  • Find Peak Element

  • Search a 2D Matrix

Type 2: guess an answer and test it

  • Koko Eating Bananas

  • Capacity to Ship Packages Within D Days

  • Sqrt(x), the square root of a number

  • Split Array Largest Sum

  • Minimum Days to Make m Bouquets

  • Magnetic Force Between Two Balls

  • Aggressive Cows (a classic)

  • Allocate Books / Painter’s Partition (a classic)

Conclusion 🎯

Binary search is not just for sorted arrays. It is a way of thinking.

  • Ask three questions: Is there an order? Is the range fixed? Do I find the answer in the data, or guess and test?

  • Then repeat: assume the middle, test it, compare with the target, and ignore the half that cannot hold the answer.

  • Stop when you find it or nothing is left.

Every round cuts the problem in half. So the real skill is not code. It is spotting when the pattern fits.

About the author

  • Java & Spring Boot backend developer | Love solving problems

No comments yet. Be the first to comment.