Binary Search is one of the highest-ROI topics for coding interviews. It’s fast, elegant, and shows up frequently: searching in sorted arrays, finding boundaries, answer space problems, optimization, and even graphs/DP when you spot the right monotonic behavior.
At its core, Binary Search transforms a linear search, checking every single item, into a lightning-fast process that can find an element in a list of billions in just a few dozen steps. It achieves this by discarding half of the remaining search space at every step, using comparisons to decide which half can be ignored.
If you get comfortable with when binary search applies and how to write it without bugs, you’ll solve a big chunk of LeetCode efficiently and confidently.
The real-world intuition
Imagine you are looking for the word “Marmot” in a physical dictionary. As you know the word starts with the letter ‘M’, you don’t start your search with page 1 and flipping through the ‘A’s. You know the book is sorted alphabetically, so you use that structure to your advantage by starting much further in.
To begin, you open the dictionary roughly to the middle and check the words on that page. Let’s say you land on a section where the words start with “Me…”. You compare your target, “Ma”, to what you see on the page. As “Ma” comes before “Me” in the alphabet, you know with absolute certainty that “Marmot” must be located in the pages to your left.
At this point, you effectively discard the entire right half of the book from your search. You then take the remaining section of pages on the left, split them in the middle again, and repeat the same logic. By choosing a direction and eliminating half of the remaining search space at every single step, you find your target really quickly. This process is exactly how Binary Search works.
What is Binary Search?
Binary Search is a divide-and-conquer searching algorithm that finds a target value (or target position) in a sorted sequence by repeatedly comparing the target to the middle element and eliminating half of the remaining search range each step.
Why is Binary Search powerful?
| Feature | Linear Search | Binary Search |
| Best use case | Works on any list, including unsorted data. | Works on sorted data. |
| How it works | Checks elements one by one from start to end. | Repeatedly checks the middle element and discards half the search space. |
| Speed | Slow; time grows 1:1 with data. | Incredibly fast; grows logarithmically. |
| Time complexity (average/worst) | O(n) | O(log n) |
Which data structures works well with Binary Search?
Binary Search works best on data structures that provide sorted order and fast random access, so we can jump directly to the middle element.
- Arrays/Dynamic Arrays (best fit): Works extremely well on arrays (and array-likes such as Python lists, Java arrays, C++ vectors) because you can access the middle element in O(1) time.
- Sorted 2D Arrays/Matrices (common variation): Works when the matrix is sorted in a way that allows binary search, for example when each row is sorted and rows are ordered, or when you apply binary search per row.
- Binary Search Trees (BSTs): BSTs are conceptually “binary search” structures because left < root < right, but searching in a BST is not the binary search algorithm on an array. Also, in an unbalanced BST, search can degrade to O(n).
How does Binary Search work?
Binary Search maintains a shrinking window of where the answer could still be using two pointers:
- low: Initialized at the start of the search range.
- high: Initialized at the end of the search range
The main steps of the Binary Search are as follows:
- Compute the midpoint as mid = low + (high – low) // 2.
- Compare the value pointed by the mid with the target value:
- If both are equal, return the mid.
- If the value at mid < target, the target must be in the right half, so move the low pointer forward low = mid + 1.
- If the value at mid > target, the target must be in the left half, so move the high pointer backward high = mid – 1.
- Repeat until the window is empty, i.e., low > high.
Let’s look at the following illustration to get a better understanding of the Binary Search algorithm:
Binary Search template in Python (interview-ready)
In interviews, it helps to memorize a clean, reusable template. Here is the classic exact match template (works when the array is sorted and you want the index of the target):
Complexity analysis for Binary Search
- Time complexity (O(log n): Each iteration of binary search cuts the search space in half, so the number of comparisons grows logarithmically with the size of the input.
- Space complexity O(1): The iterative implementation uses only a constant amount of extra memory, relying on a few pointers (low, high, and mid) regardless of input size.
Modified Binary Search
In many coding interview problems, the input is not a perfectly sorted array. Instead, it has some structure that still lets you discard half the search space. This is where Modified Binary Search comes in: you keep the binary search framework, but tweak the “which half to discard?” logic based on the problem’s structure.
Classic example: Search in Rotated Sorted Array
A classic example is LeetCode 33 (Search in Rotated Sorted Array), where you search for a target in a rotated sorted array (the array is sorted but then rotated at an unknown pivot), such as:
nums = [4, 5, 6, 7, 0, 1, 2]
Even though it’s rotated, one important fact remains true: At least one half (left or right) is still sorted in every iteration.
So, instead of directly deciding which side to search in, left or right, based only on nums[mid] and target, we first identify the sorted half and use that to guide the search.
Step by step solution
- Start with the full range of the array and compute the middle index. If
nums[mid]equals the target, returnmid. - Next, determine which half is sorted:
- If
nums[low] <= nums[mid], the left half (low..mid) is sorted. Check whether the target lies within this sorted range (nums[low] <= target < nums[mid]).- If yes, move left (
high = mid - 1). - If no, move right (
low = mid + 1).
- If yes, move left (
- Otherwise, the right half (
mid..high) is sorted. Check whether the target lies within this sorted range (nums[mid] < target <= nums[high]).- If yes, move right (
low = mid + 1). - If no, move left (
high = mid - 1).
- If yes, move right (
- If
- Repeat until the search range becomes invalid (
low > high). If the target is not found, return-1.
This keeps the same binary search framework, but modifies the decision step to account for rotation, hence Modified Binary Search.
Python implementation
Now, let’s look at the optimized solution code for Search in Rotated Sorted Array.
Common Binary Search use cases
Binary Search appears in many forms across coding interviews, often hidden behind different problem statements. Recognizing these common use cases helps you quickly identify when binary search is the right tool and apply the correct pattern with confidence.
| Use case | What you practice | Common LeetCode problems |
| Classic exact search | Find an element in a sorted array | Binary Search (704), Search Insert Position (35) |
| Lower/Upper Bound (boundaries) | First index >= target, first index > target, duplicates handling | Find First and Last Position of Element in Sorted Array (34) |
| Insert position / first greater | Where a value should be inserted to keep array sorted | Search Insert Position (35), Find Smallest Letter Greater Than Target (744) |
| Peak / local optimum | Binary search on index using neighbor comparisons | Find Peak Element (162), Peak Index in a Mountain Array (852) |
| Rotated sorted array | Identify sorted half, pivot logic | Search in Rotated Sorted Array (33), Find Minimum in Rotated Sorted Array (153), Search in Rotated Sorted Array II (81) |
| Single element in pairs | Use parity + binary search to find odd one out | Single Element in a Sorted Array (540) |
| 2D matrix search | Treat matrix as sorted 1D or do row-based binary search | Search a 2D Matrix (74), Search a 2D Matrix II (240) |
| Binary Search on Answer (min feasible) | Search smallest value that satisfies a monotonic condition | Koko Eating Bananas (875), Capacity To Ship Packages Within D Days (1011), Minimum Days to Make m Bouquets (1482), Find the Smallest Divisor Given a Threshold (1283) |
| Binary Search on Answer (min/max optimization) | Minimize maximum / maximize minimum with feasibility checks | Split Array Largest Sum (410), Magnetic Force Between Two Balls (1552) |
| Median / partition (advanced) | Binary search on partition rather than values | Median of Two Sorted Arrays (4) |