Binary Search
Reach for it when the problem says
- Sorted data
- "minimum x such that…"
- rotated arrays
- O(log n) asked
- Solved
- 0/32Solved
- Problems
- 32Problems
- Variants
- 6Variants
Problems
6 variantsClassic search
0 of 5 solved- Binary SearchUp nextDeep diveEasyDecode Binary Search
- Guess Number Higher or LowerEssentialsDeep diveEasyDecode Guess Number Higher or Lower
- Sqrt(x)SprintDeep diveEasyDecode Sqrt(x)
- Valid Perfect SquareEasyDecode Valid Perfect Square
- Arranging CoinsEasyDecode Arranging Coins
2D and matrices
0 of 4 solved- Count Negative Numbers in a Sorted MatrixEasyDecode Count Negative Numbers in a Sorted Matrix
- Search a 2D MatrixSprintDeep diveMediumDecode Search a 2D Matrix
- Search a 2D Matrix IIMediumDecode Search a 2D Matrix II
- Kth Smallest Element in a Sorted MatrixMediumDecode Kth Smallest Element in a Sorted Matrix
Search on the answer
0 of 8 solved- Koko Eating BananasEssentialsDeep diveMediumDecode Koko Eating Bananas
- Capacity To Ship Packages Within D DaysDeep diveMediumDecode Capacity To Ship Packages Within D Days
- Minimum Number of Days to Make m BouquetsDeep diveMediumDecode Minimum Number of Days to Make m Bouquets
- Magnetic Force Between Two BallsDeep diveMediumDecode Magnetic Force Between Two Balls
- Find the Smallest Divisor Given a ThresholdMediumDecode Find the Smallest Divisor Given a Threshold
- Minimum Time to Complete TripsMediumDecode Minimum Time to Complete Trips
- Maximum Candies Allocated to K ChildrenMediumDecode Maximum Candies Allocated to K Children
- Split Array Largest SumDeep diveHardDecode Split Array Largest Sum
Rotated arrays
0 of 3 solvedBoundary search
0 of 8 solved- First Bad VersionEasyDecode First Bad Version
- Search Insert PositionSprintDeep diveEasyDecode Search Insert Position
- Find First and Last Position of Element in Sorted ArraySprintDeep diveMediumDecode Find First and Last Position of Element in Sorted Array
- Successful Pairs of Spells and PotionsEssentialsDeep diveMediumDecode Successful Pairs of Spells and Potions
- Time Based Key-Value StoreDeep diveMediumDecode Time Based Key-Value Store
- H-Index IIDeep diveMediumDecode H-Index II
- Find K Closest ElementsDeep diveMediumDecode Find K Closest Elements
- Count Complete Tree NodesSprintDeep diveMediumDecode Count Complete Tree Nodes
Peaks and partitions
0 of 4 solved- Find Peak ElementEssentialsSprintDeep diveMediumDecode Find Peak Element
- Peak Index in a Mountain ArrayMediumDecode Peak Index in a Mountain Array
- Single Element in a Sorted ArrayMediumDecode Single Element in a Sorted Array
- Median of Two Sorted ArraysSprintDeep diveHardDecode Median of Two Sorted Arrays
Pattern guide
Binary search is the pattern interviewers use to see whether you can turn "try everything" into "rule out half of everything, every step". It shows up far beyond sorted arrays: picking a ship capacity, finding a first bad build, splitting work evenly. When the input is a billion wide, it is the difference between a billion steps and thirty.
What it is
You keep a range [lo, hi] of places the answer could still be. You look at the middle, ask one yes/no question, and the answer lets you throw away one half for good. The range shrinks from n to n/2 to n/4, so after about log₂ n questions only one candidate is left. For n = 1,000,000 that is 20 questions.
Here is the classic case: find 23 in a sorted list.
The whole list is possible. The middle value is 16, which is smaller than 23, so 23 cannot be at index 4 or anywhere left of it.
The real requirement is not "sorted". It is monotonic: some yes/no question that is false on one side and true on the other, with exactly one switch. A sorted array gives you that for free (nums[i] >= target), but so does "can Koko finish at speed k?" or "is version v bad?". Find the question and you can binary search it.
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "sorted", "non-decreasing", "ascending" | Classic or boundary search on the array |
| "must run in O(log n)" | Binary search, almost always |
| "first", "last", "leftmost", "earliest" | Boundary search: first true or last true |
| "minimum capacity / speed / days such that" | Search on the answer |
| "maximise the minimum" or "minimise the maximum" | Search on the answer |
| "rotated sorted array" | Rotated arrays: find the sorted half |
| "rows and columns are sorted" | 2D search or staircase walk |
| "peak", "mountain" | Compare mid with mid + 1 |
Constraint clues
| Constraint | What it suggests |
|---|---|
n <= 10^5 with sorted input | O(log n) per query, or O(n log n) overall |
Values or answers up to 10^9 or 10^14 | You cannot try each value; halve the value range |
n <= 10^4 but "O(log n)" demanded | The test is technique, not speed |
| An expensive call you must "call as few times as possible" | Each call should halve the possibilities |
Input and output shape clues
- Input is a sorted array, output is an index or a boolean: classic or boundary search.
- Output is a single number (speed, capacity, days, distance) and you can check a candidate in O(n): search on the answer.
- Input is a grid with sorted rows and columns: map indexes or walk a staircase.
- Input is not sorted, but neighbours are comparable (peaks, pairs, partitions): a local comparison at
midstill points one way.
Looks like it but isn't
- Two pointers on a sorted array. "Find a pair summing to target in a sorted array" uses sorting, but the pointers move one step at a time from both ends. Binary search jumps to the middle and asks about one position.
- Sliding window. "Minimum length subarray with sum at least k" sounds like "minimum such that", but the window is contiguous and grows and shrinks in O(n). You can binary search the length, but the window is simpler and faster.
- Heap for kth smallest. A heap is the default for "kth smallest". Reach for binary search on the value only when the input is sorted enough to count elements below a guess quickly.
- Unsorted search. Binary search on an unsorted array with no monotonic signal is simply wrong. Sorting first costs O(n log n), worse than a single O(n) scan.
Match each prompt to the right tool.
The sub-patterns
Classic search
When it applies: a sorted array (or a sorted range of integers) and you want an exact match. You can return the moment you see it.
Search r from 0 to 10. 5 * 5 = 25 is more than 20, so the root is below 5.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log n) time, O(1) space. Best-known problems: Binary Search, Guess Number Higher or Lower, Sqrt(x), Valid Perfect Square.
Boundary search
When it applies: duplicates, or a question like "first bad version" or "latest timestamp at or before t". You do not stop at a match; you keep narrowing until you find the edge where a yes/no test flips. This is the most important template to memorise, because the other sub-patterns reuse it.
Half-open range [0, 7). At mid = 3 the value is 8, so the test is true. The edge is at 3 or earlier, so keep mid: hi = mid.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log n) time per boundary, O(1) space. Best-known problems: First Bad Version, Find First and Last Position of Element in Sorted Array, Time Based Key-Value Store, Successful Pairs of Spells and Potions.
What does this print?
nums = [1, 2, 2, 2, 3]
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] >= 2:
hi = mid
else:
lo = mid + 1
print(lo)Search on the answer
When it applies: the prompt asks for the minimum (or maximum) number such that something is possible, and you can check one candidate quickly. Instead of searching an array, you search the range of possible answers. The check is usually a greedy O(n) pass.
The recipe has three parts: the range [lo, hi] of possible answers, a feasible(x) check, and the direction (bigger x always easier, or always harder).
Index i means speed i + 1. Speed 6 needs 1 + 1 + 2 + 2 = 6 hours, which fits in 8. Keep it: hi = mid.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.For a maximum (like "largest minimum distance"), the yes answers come first, so you want the last true. Flip the moves and round the middle up: mid = (lo + hi + 1) // 2, then lo = mid on yes and hi = mid - 1 on no. Without the + 1, a range of two values can loop forever.
Complexity: O(n · log(range)) time, O(1) space. Best-known problems: Koko Eating Bananas, Capacity To Ship Packages Within D Days, Split Array Largest Sum, Magnetic Force Between Two Balls.
max(weights) instead of 1?Rotated arrays
When it applies: a sorted array that was rotated, so it is two sorted runs. Split at mid and at least one half is sorted. You can tell which by comparing nums[lo] with nums[mid] (or nums[mid] with nums[hi]), and you can tell whether the target lies inside the sorted half with two comparisons.
nums[mid] = 7 is bigger than nums[hi] = 2, so mid is in the high run and the drop is strictly to the right: lo = mid + 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.With duplicates, nums[lo] == nums[mid] tells you nothing, so drop one end (lo += 1) and try again. That keeps it correct but makes the worst case O(n).
Complexity: O(log n) time, O(1) space (O(n) worst case with duplicates). Best-known problems: Find Minimum in Rotated Sorted Array, Search in Rotated Sorted Array, Search in Rotated Sorted Array II.
Peaks and partitions
When it applies: the array is not sorted by value, but a local comparison at mid still proves which side holds an answer. For a peak, compare nums[mid] with nums[mid + 1]: uphill means a peak is to the right. For a lone element among pairs, check whether the pair at an even mid is intact. For the median of two sorted arrays, check whether a cut has too many values from one list.
nums[3] = 7 is bigger than nums[4] = 6. Downhill to the right, so a peak is at 3 or to its left: hi = mid.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log n) time, O(1) space (O(log(min(m, n))) for the median). Best-known problems: Find Peak Element, Peak Index in a Mountain Array, Single Element in a Sorted Array, Median of Two Sorted Arrays.
2D and matrices
When it applies: a grid with sorted rows (and often sorted columns). There are three moves. If each row starts after the previous one ends, the grid is one sorted list: binary search positions 0 to m * n - 1 and map i to matrix[i // cols][i % cols]. If rows and columns are sorted independently, walk a staircase from the top-right (or bottom-left) corner, removing a row or column per step. And for "kth smallest", binary search on the value and use the staircase to count cells below a guess.
Start top-right at 11. Left is smaller, down is bigger. 11 is less than 14, so this whole row is too small: move down.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log(m · n)) for the flattened search, O(m + n) for the staircase, O(n · log(range)) for kth smallest. Best-known problems: Search a 2D Matrix, Search a 2D Matrix II, Kth Smallest Element in a Sorted Matrix, Count Negative Numbers in a Sorted Matrix.
A decision checklist
When a problem smells like binary search, run through these questions in order. The first yes tells you the sub-pattern.
Put the questions in the order you should ask them.
- Tap the steps below in the right order.
Match each problem to its sub-pattern.
Traps
- Mixing loop styles. A closed range
[lo, hi]goes withwhile lo <= hiandhi = mid - 1. A half-open range[lo, hi)goes withwhile lo < hiandhi = mid. Mixing them either skips the last candidate or loops forever. Pick one per problem and say which out loud. - The infinite loop on two elements. With
lo = midon a yes andmid = (lo + hi) // 2, a range like[4, 5]keeps picking 4 forever. When you movelo = mid, round up:mid = (lo + hi + 1) // 2. - Wrong bounds on the answer. The range must include every valid answer. Koko's speed starts at 1, not 0 (division by zero). Ship capacity starts at
max(weights). Max candies starts at 0, because zero may be the only answer. - Stopping at any match when you need an edge. On
[8, 8, 8, 8], classic search finds an 8, not the first one. Expanding outward from the match is O(n). - Overflow. In Java or C++,
(lo + hi) / 2overflows near2^31; writelo + (hi - lo) / 2. Python ints never overflow, and JS numbers are exact up to2^53, but products likemid * midstill need care in fixed-width languages. - Non-monotonic checks. Binary search on a test that flips more than once returns garbage silently. Before coding, convince yourself the yes answers sit on one side.
Edge cases to test every time: an empty array (if allowed), one element, two elements, the target at the very first and very last index, a target smaller and bigger than everything, all values equal, and the largest allowed values.
nums[i] <= x. It hangs on some inputs. Why?lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] <= x:
lo = mid
else:
hi = mid - 1How to talk it through
A model narration for Koko Eating Bananas: "Trying every speed is O(n · max pile), up to 10^13. Feasibility is monotonic in the speed, so I'll binary search it between 1 and the largest pile. To check a speed I add up the ceilings of pile over speed, which is O(n). If the hours fit, I keep the speed as a candidate, otherwise I go faster. About 30 checks, so O(n log max) time and O(1) space. Let me trace h equal to the number of piles, where the answer should be the biggest pile."
- search space
- The range of indexes or values that could still hold the answer. Every step should cut it in half.
- monotonic predicate
- A yes/no test that is false on one side and true on the other, switching once. It is what makes binary search valid.
- lower bound
- The first index whose value is
>=a target, or the length if none is. The building block of boundary search. - search on the answer
- Binary search over possible answers (a speed, a capacity, a day) using a feasibility check, instead of over an array.
- loop invariant
- A fact that holds every iteration, such as 'the answer is in
[lo, hi]'. Stating it is how you get the moves right. - staircase walk
- Starting at a corner of a grid sorted by rows and columns and moving left or down, ruling out a row or column each step.