Zero Labs
Industry News / AI

Pattern 3: Binary Search

Source · Towards AI By An

From the publisher’s feed, collected in the ZeroLabs newsroom.

Hi guys, welcome back to my DSA series. I Hope you are following my journey. If not, check out my previous posts as well. Today, let’s discuss one of the most interesting topics in DSA :Binary Search. When I first heard about binary search, my mind was blown. I kept thinking, “How did someone even come up with this idea of searching?” It felt so smart and efficient. Instead of giving the usual boring examples like searching in a dictionary or replacing linear search, let’s talk about something more relatable.The Reels Guessing Game:You have definitely come across this trend. Two people — friends, couples, siblings playing a number guessing game on camera. It goes something like this:The Rules:Both players secretly pick a number between 1 and 100 and write it down — so each person has a number the other has to guess.They take turns. On your turn, you guess one number from your opponent’s range.Your opponent tells you — “Higher” or “Lower” — depending on whether their secret number is above or below your guess.Then it’s their turn to guess your number. You tell them higher or lower.You keep alternating turns like this and the first person to guess their opponent’s exact number wins.It’s a race. You’re both hunting simultaneously, one turn at a time.Guess Game [AI Generated]I was playing this number guessing game with my friend one day not for a reel, just casually for fun. We both picked a number between 1 and 100, and the goal was to guess each other’s number. My friend started guessing randomly: 73, 12, 55, 89… just trying numbers without much strategy. I noticed I was doing something different, though I didn’t think much of it at the time.My approach was simple. Since the range was 1 to 100, I guessed 50 first — the middle. My friend said, “Higher.” That immediately eliminated half the numbers. Now the number had to be between 51 and 100, so I guessed 75. He said, “Lower.” Again, half the remaining range was gone. Then I guessed 62, then 68, narrowing the range every time based on his answer. Without realizing it, I was doing the exact thing Binary Search does.Binary Search works by checking the middle element and then eliminating half of the search space depending on whether the target is higher or lower. That’s exactly what was happening in this game. Every “higher” or “lower” hint helped me discard half of the possibilities and focus only on the remaining range.That’s why I found his number in just a few guesses, while my friend was still jumping randomly between numbers.What feels interesting is that we’ve all seen those Instagram reels where people play this guessing game, but most of the time nobody explicitly thinks of it as Binary Search. They’re just playing. But if you pause and connect the dots, the strategy behind the game maps perfectly to Binary Search. That’s what makes Binary Search interesting to me. It’s not just an algorithm you solve on a coding platform — it’s a way of narrowing down possibilities by repeatedly choosing the middle and eliminating what can’t be true. At the end of this journal, I will also share a puzzle I encountered in one of my interviews where Binary Search showed up again in a very interesting way.I am not going to bore you with variants and coding you already know how to look those up, and honestly you probably know that part better than I can explain it here. What I really want to talk about is something more valuable: where to actually apply binary search and the mistakes I keep seeing students make. Let’s get into it.Where to Apply Binary Search:It’s Not Just About Sorted Arrays: Everyone thinks the input array must be sorted to apply binary search — and yes, that’s true. But the more important condition that most people miss is this: The range of your answer must lie within a definable, inclusive boundary. Even if the array isn’t directly sorted, if the answer space is ordered and bounded, binary search applies. This is why binary search shows up in problems that don’t even look like search problems at first glance.One Decision Must Cut Your Search Space in Half: At every step, you must be able to make one clear decision that eliminates half your remaining search space permanently. If you can look at the midpoint and confidently say “the answer cannot be in this half” — binary search works. If you can’t make that elimination with certainty, binary search doesn’t apply.Binary Search on the Answer: A lot of people will tell you “just look for keywords like minimum possible or maximum possible.” But that feels like mugging up — you’ll forget it the moment pressure hits.Here’s a better way to think about it. Ask yourself one question when you see a problem “If I fix a value as my answer can I quickly verify whether it’s valid or not?” If yes and if valid and invalid answers split into two clean halves you can binary search the answer itself instead of an array. I will do a complete dedicated journal on this — with full examples, walkthroughs and intuition built from scratch.Common Mistakes:Memorizing Time Complexity Without Understanding It:Most memorize that binary search time complexity is O(log n) — but if you ask them why, they go blank. Where does the log actually come from?I won’t go deep into the math here, but I genuinely urge you to look into it. Understanding why it’s O(log n) changes how you think about algorithms entirely.The Classic Integer Overflow Bug: Almost every programmer writes this at some point:mid = (high + low) / 2Looks fine — but what happens when both low and high are close to INT_MAX? Their sum overflows and wraps to a negative number, giving you a completely wrong midpoint.The correct way:mid = low + (high - low) / 2Same result mathematically, but the overflow never happens. Small change but exactly the kind of thing that impresses interviewers, because it shows you think about edge cases, not just the happy path.When High and Low Are Floating Point Numbers:This trips up even experienced programmers. With integers, your search space shrinks by at least 1 every iteration the loop is guaranteed to terminate. With floats, the gap between low and high keeps halving forever — 0.5, 0.25, 0.125, 0.0625… and never actually hits zero. If your condition is low == high or low >= high, your loop may never exit. The fix — stop when the gap is smaller than a tiny threshold called epsilon:def binary_search_float(low, high): eps = 1e-9 # stop when range is this small while (high - low) > eps: mid = low + (high - low) / 2 if condition(mid): low = mid else: high = mid return lowAnd never check arr[mid] == target with floats. Floating point precision errors make exact equality unreliable — 0.1 + 0.2 is not exactly 0.3 in most languages. Always work with thresholds, never exact equality. and there is problem Sqrt(x) directly tests floating point binary search thinking.Now that we know where to apply it and what mistakes to avoid — let’s build the actual intuition through problems. As you solve these, pay close attention to the concepts of lower bound and upper bound — you will start seeing them everywhere. Follow this order:Binary SearchSearch Insert PositionFirst Bad VersionSqrt(x)Find Smallest Letter Greater Than TargetCount of Range SumSearch a 2D MatrixArranging CoinsFirst and Last Position of ElementFind Minimum in Rotated Sorted ArraySearch in Rotated Sorted ArrayFind Peak ElementKoko Eating BananasCapacity to Ship Packages Within D DaysMinimum Days to Make BouquetsBinary Search in the Real World — AI/ML:We saw binary search in a guessing game. Now let me show you where the exact same thinking shows up in machine learning.When I was going through AI/ML concepts I came across binary classification — models that predict one of two things. Spam or not spam. Fraud or not fraud. The model doesn’t directly say yes or no — it gives you a probability score between 0 and 1. You then decide a cutoff value — if the score is above it, say yes. Below it, say no. This cutoff is called the decision threshold.Here’s the problem. Choosing the wrong threshold breaks everything. Too low and your model flags everything. Too high and it misses everything. You need to find the sweet spot sitting somewhere between 0 and 1.Now think about how you find it.You can’t try every decimal value one by one — that’s linear search. Slow and pointless. Instead you pick the middle — 0.5. You check the performance. Too aggressive? Move left. Too lenient? Move right. Keep halving until you land on the best value. One decision. Half eliminated. Repeat.That is binary search — applied to a machine learning problem. The reason it works here is because as the threshold increases, the performance metrics shift in one consistent direction. That clean signal is exactly what binary search needs to keep eliminating half the space at every step. Just like your friend saying “higher” or “lower” in the guessing game.Binary search in AI/ML[AI Generated]The Interview Puzzle :Now let me tell you about the moment it all truly clicked for me. I was interviewing at a reputed company when the interviewer placed this problem in front of me:“You have a common balance and a group of weights. All of them look exactly identical same size, same shape. But one of them is slightly heavier than the rest. Find the odd one out in the minimum number of weighings.”My first instinct was the same as everyone else’s — pick two weights, compare them, move to the next pair. One by one. That’s linear search in disguise — slow, no strategy, worst case you go through every single weight.Then the binary search instinct kicked in. Split the weights into two equal groups. Place one group on each side of the balance. The heavier side has the odd weight — you’ve just eliminated half the weights in a single weighing. Take that heavier group, split it again into two equal halves. Weigh them again. The heavier side wins again — another half gone. Keep doing this until you’re down to one weight.One decision. Half eliminated. Repeat. At the end of my answer I connected it back — told the interviewer that this is exactly what binary search does. Same logic, same instinct, just a physical balance instead of an array. The interviewer was genuinely impressed.Interview Puzzle[AI Generated]What’s coming next: In the next article, I will write about the Prefix sum and once again try connecting the dots with some real AI/ML applications. Until then, open LeetCode, search “Binary Search,” and solve a few problems.I wrote this article to organize everything I learned about Binary Search in one place and to explain it the way I wish I had learned it earlier. From a number guessing game on Instagram to a balance puzzle in an interview room — binary search is not just an algorithm, it is a way of thinking that shows up everywhere once you truly understand it. If this helps you see the pattern a little faster or makes even one problem click for you, then this article has done its job. Thank you for reading. If you notice any mistakes, gaps, or better ways to think about the pattern, feel free to share them — I am always open to learning.— AnPattern 3: Binary Search was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.