What is Binary Search?
Searching·6 min·Python code
Binary search checks the middle of a sorted array and discards the half that cannot hold your target. That halving gives O(log n) time, far less work than scanning every element.
How Binary Search Halves the Search Range
Think of looking up a word in a paper dictionary. You flip to the middle, see whether your word falls before or after, and ignore half the book at once. Repeat on the half that remains and you close in on your word within a handful of flips.
Binary search captures that strategy precisely. Check the middle element of a sorted list. Your target ends the search on a match. Larger targets must sit in the right half, and smaller targets must sit in the left half.
Halving gives the power. Lists of a million items need about 20 comparisons, and lists of a billion need about 30. Search windows collapse quickly.
How Binary Search Uses Two Pointers
Implementations track the live range with two indices called low and high, which bracket the array part still in play. Every loop step computes a midpoint with mid = (low + high) // 2 and compares nums[mid] to your target. On a match, return mid.
If nums[mid] is too small, your target can only sit on the right, so move low to mid + 1. If it is too big, move high to mid - 1. Loops continue while low <= high, and once pointers cross, the range is empty and your target is absent.
Two details make or break the code. First, + 1 and - 1 in pointer updates exclude mid, which you already checked, so the range shrinks and loops end. Second, loop condition low <= high matters, because < with these updates skips the final single element range.
That is why people call binary search quick to describe and tricky to get right.
Why Binary Search Is O(log n) and Needs Sorted Data
Every comparison discards half the remaining elements, so the count goes n → n/2 → n/4 → … until one is left. Reaching 1 from n takes log₂(n) halvings, which makes the time cost O(log n). Space is O(1) for the iterative version because only two pointers are stored, while a recursive version uses O(log n) stack space.
Binary search needs sorted data, which is the catch. It rests on knowing everything right of mid is larger, and unsorted data breaks that guarantee, so answers mean nothing.
For a single search, sorting first with sorting algorithms costs O(n log n), more than a linear scan. Binary search pays off when the data is already sorted or you query it many times.
Build the skill on CodeStory's binary search practice problems.
Binary Search Code Example in Python
def binary_search(nums, target):
"""Return the index of target in sorted nums, or -1 if absent."""
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2 # midpoint of the current range
if nums[mid] == target:
return mid # found it
elif nums[mid] < target:
low = mid + 1 # discard the left half
else:
high = mid - 1 # discard the right half
return -1 # target not in the array
Edit this loop in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Binary Search Time and Space Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) iterative, O(log n) recursive |
Ideal cases cost O(1) when the target sits at the first midpoint, while worst and average cases cost O(log n). Input must be sorted. Recursive code trades O(1) space for O(log n) call stack space.
Watch Binary Search Step by Step
Seeing the window shrink on your own input makes the idea stick. Follow any of these one step at a time.
When to Use Binary Search
- Checking whether a value exists, and where, in a large array that is already sorted.
- Finding a boundary, like the first or last index of a value or an insertion point that keeps an array sorted (lower and upper bound).
- Binary search on the answer, which finds the smallest or largest value meeting a monotonic condition, like minimum ship capacity or speed that still meets a deadline.
- Querying static sorted data again and again, where an O(log n) lookup beats an O(n) scan on every request.
Mistakes to Avoid
- Off by one bugs, where loop conditions (<= or <) do not match pointer updates or a ± 1 is missing, which causes infinite loops or a missed final element.
- Using it on unsorted data gives a wrong result, because the discard a half step assumes order.
- Integer overflow on (low + high) in fixed width languages like Java or C++, so compute low + (high - low) / 2 instead. Python's arbitrary precision integers avoid the problem.
Binary Search FAQs
What is the time complexity of binary search?
O(log n) in the worst and average case, because every comparison halves the search space. O(1) is the ideal case, when your target lands on the first midpoint. Space is O(1) for iterative code and O(log n) for recursive code because of call stack frames.
Does binary search require a sorted array?
Yes. Binary search relies on order to decide which half to discard, so unsorted data makes elimination meaningless and results wrong. Sort first at O(n log n) or use a hash table for O(1) average time exact lookups.
Is binary search hard to learn?
Halving the range at every step is plain, but writing bug free code is tricky. Most beginners hit off by one errors in the loop condition or pointer updates. Tracing the low and high pointers on a small example makes it click.
When should I use binary search instead of a hash table?
Use a hash table when you need only exact match lookups at O(1) average time. Use binary search when data is sorted and you need order aware answers, like the nearest value, the first element ≥ x, an insertion point or range boundaries, which a hash table cannot give.
How do I find the middle index without overflow?
Compute low + (high - low) / 2 in fixed width languages like Java and C++, because the plain sum can overflow. Python integers cannot overflow, so the plain sum is safe there.
Can binary search find the first or last occurrence of a value?
Yes. Keep searching after a match, moving high left for the first occurrence or low right for the last. That idea is the lower bound and upper bound, and CodeStory's visualiser shows the lower bound version step by step.
How do I practise binary search on CodeStory?
Open CodeStory's binary search practice problems, then watch the window move in the binary search visualiser before you write your own loop.
Related Guides
Guides are step one. In a CodeStory batch you write the loop yourself, then explain every pointer move in a scored mock round.
Talk to a Mentor