In this chapter, we'll understand how Binary Search works, implement it step by step, analyze its efficiency, and explore the situations where we should use it.
Before understanding Binary Search, let's look at how we normally search for an element in an array.
Suppose we have an array of numbers, and we want to find the number 40.
The most straightforward approach is Linear Search. We start from the first element and compare it with our target. If it doesn't match, we move to the next element. We keep going until we find 40 or reach the end of the array.
This approach works perfectly well. It's simple, easy to implement, and doesn't require the elements to be arranged in any particular order.
But there's one problem. If our target is near the end of the array, we might have to examine almost every element. For an array containing 1 million elements, Linear Search could require up to 1 million comparisons. And as the array grows, the amount of work grows with it.
This gives Linear Search a worst-case time complexity of O(n).
But what if our array is already sorted? Can we use that additional information to search more efficiently?
We can. That's where Binary Search comes in.
Instead of checking elements one by one, Binary Search starts with the middle element. By comparing it with our target, we can determine which half of the array might contain the answer.
This only works because the array is sorted. Every element to the left of the middle is smaller than or equal to it, and every element to the right is greater than or equal to it. So one comparison tells us which side the target can't be on.
With every comparison, we can eliminate roughly half of the remaining search space.
Let's walk through a complete example. We'll use this sorted array of 15 elements and search for the number 40:
First, we need a way to keep track of which part of the array we're searching. For this, we'll use two pointers:
left marks the beginning of our search range.right marks the end.Initially, left is at index 0 and right is at index 14, so we're starting with the entire array.
Next, we calculate the middle index. For now, think of it as the average of left and right, rounded down:
Index 7 holds 31. Now let's compare 31 with our target, 40.
Since 40 is greater than 31, we know it can't be at index 7 or anywhere to its left. So we move left to mid + 1, which is 8. Our search range now starts at index 8 and ends at index 14.
With a single comparison, we've eliminated 8 elements.
Let's continue. Our current search range is from index 8 to index 14.
We calculate the middle index again. This time it's index 11, where the element is 52. Since 40 is smaller than 52, it must be somewhere to the left of index 11. So we can eliminate index 11 and everything to its right by updating right to mid - 1, which is 10.
Our search range is now from index 8 to index 10. The middle of indices 8 and 10 is index 9, and the element at index 9 is 40. That's exactly what we're looking for, so we return index 9 and the search is complete.
Here is the whole search, step by step:
We found the target in just 3 comparisons. With Linear Search, starting from the beginning, we would have needed 10 comparisons to find the same element.
For a small array, that might not seem like a big difference. But when we're dealing with millions or billions of elements, the difference becomes enormous.
So far, we've seen an example where the target exists in the array. But what if it doesn't? Let's search for 41 instead of 40.
We start with the entire array. The first middle element is 31. Since 41 is greater than 31, we search the right half.
The next middle element is 52. Since 41 is smaller than 52, we search the left half.
Now our search range contains just three elements: 35, 40, and 46. The middle element is 40. Since 41 is greater than 40, we move left to the next position.
Now only one element remains: 46. But 46 is greater than 41, so we move right to the position before it.
At this point, left becomes greater than right. This means there are no elements left to check, and our search range is empty. Since we've ruled out every possible position, we know that 41 doesn't exist in the array.
In our implementation, we'll return -1 to indicate that the target wasn't found.
This also gives us a simple stopping condition. Binary Search continues as long as left is less than or equal to right. Once left becomes greater than right, the search is over.
Now that we understand how Binary Search works, let's implement it in code. We'll use the iterative approach.
Our function takes two inputs: a sorted array called nums and the value we're searching for, called target.
left to 0 and right to the last index of the array.left <= right.left to mid + 1.right to mid - 1.With just a few lines of code, we can efficiently search through millions of sorted elements.
left + (right - left) / 2?You might notice that we're calculating the middle index using left + (right - left) / 2. Why not simply use (left + right) / 2?
Mathematically, both give us the same result. But in languages like Java, C++, C#, and Go, adding two very large indices can cause integer overflow. For example, if left and right are both above 1.1 billion, their sum exceeds the largest 32-bit integer (2,147,483,647) and wraps around to a negative number.
The version we're using avoids this problem for valid array indices, because right - left is never larger than the array's length. Python has no fixed integer size, and JavaScript numbers can hold far larger values than any real array length, so the issue doesn't come up there. That's why the Python, JavaScript, and TypeScript versions above use the simpler (left + right) / 2 form, rounded down.
It's a small detail, but an important one to remember, especially in coding interviews.
Now, let's analyze how efficient Binary Search really is.
Suppose our array contains n elements. After the first comparison, we eliminate roughly half of them. After the second comparison, we eliminate half of what's left. And we keep repeating this until we either find our target or run out of elements.
So the number of remaining elements decreases like this:
How many times can we divide n by 2 before we're left with just one element? Approximately log₂(n) times. That's why Binary Search has a worst-case time complexity of O(log n).
Let's put this into perspective:
| Number of elements | Linear Search (worst case) | Binary Search (worst case) |
|---|---|---|
| 100 | 100 comparisons | 7 comparisons |
| 1,000 | 1,000 comparisons | 10 comparisons |
| 1,000,000 | 1,000,000 comparisons | 20 comparisons |
| 1,000,000,000 | 1,000,000,000 comparisons | 30 comparisons |
Even if our array contains 1 billion elements, Binary Search needs at most about 30 comparisons to find a target, or around 30 to determine it doesn't exist. Compare that with checking elements one by one. That's a massive improvement.
In the best case, our target is the very first middle element we check. So the best-case time complexity is O(1).
What about space complexity? Our iterative implementation only uses a few variables: left, right, and mid. We don't need any additional arrays or data structures. So the auxiliary space complexity is O(1).
| Case | Time | Space |
|---|---|---|
| Best | O(1) | O(1) |
| Worst | O(log n) | O(1) |
At this point, Binary Search might seem like the obvious choice whenever we need to find something. But there's one important requirement.
The data must be sorted, or have some ordered property that lets us eliminate part of the search space.
If we use Binary Search directly on an unsorted array, it won't work reliably. For example, suppose the middle element is 50, and we're searching for 20. In a sorted array, we'd know that 20 must be somewhere to the left. But in an unsorted array, 20 could be anywhere, so we can't safely eliminate either half.
We could sort the array first. But sorting itself takes time, typically O(n log n). If we only need to search once, Linear Search might actually be simpler and faster overall.
However, if our array is already sorted and we need to perform thousands of searches, Binary Search becomes much more useful. We pay the sorting cost once, and every search after that costs only O(log n).
It also works especially well with arrays, because we can access any element directly in constant time. With linked lists, finding the middle element means walking from the head, which takes O(n) time. So Binary Search is generally less practical there.
Let's quickly go over a few common edge cases.
right starts at -1, so the loop condition 0 <= -1 is false. The loop never runs, and we correctly return -1.left and right both start at 0. We compare that one element with our target and return either 0 or -1.[27, 40, 40, 40, 40, 52], the first middle index is 2, which holds 40, so it returns 2. The first 40 is at index 1 and the last is at index 4.If a problem asks for the first or last occurrence, we'll need to adjust our search logic. We cover those variations, along with other binary search templates, in the next chapter on binary search patterns.
left and right, and keep narrowing the range until we find the target or the range becomes empty.10 quizzes