Skip to content

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 variants

Classic search

0 of 5 solved

2D and matrices

0 of 4 solved

Search on the answer

0 of 8 solved

Rotated arrays

0 of 3 solved

Boundary search

0 of 8 solved

Peaks and partitions

0 of 4 solved

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.

Searching for 23
2
0
↑lo
5
1
8
2
12
3
16
4
↑mid
23
5
38
6
56
7
72
8
91
9
↑hi
target = 23

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.

1/4

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.

log n barely moves while n climbs
input size n →ops
  • O(log n)4
  • O(n)16
  • O(n log n)64
Quick check
About how many comparisons does binary search need on a sorted list of 1,000,000 values?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat 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

ConstraintWhat it suggests
n <= 10^5 with sorted inputO(log n) per query, or O(n log n) overall
Values or answers up to 10^9 or 10^14You cannot try each value; halve the value range
n <= 10^4 but "O(log n)" demandedThe 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 mid still 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 the pairs0/5 matched

Match each prompt to the right tool.

Choose an item, then its match on the other side.

The sub-patterns

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.

Searching a range of integers: floor of the square root of 20
0
0
↑lo
1
1
2
2
3
3
4
4
5
5
↑mid
6
6
7
7
8
8
9
9
10
10
↑hi
mid² = 25

Search r from 0 to 10. 5 * 5 = 25 is more than 20, so the root is below 5.

1/4
Python
def binary_search(nums, target): lo, hi = 0, len(nums) - 1 while lo <= hi: # closed range: [lo, hi] mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1 print(binary_search([2, 5, 8, 12, 16, 23, 38], 23))print(binary_search([2, 5, 8, 12, 16, 23, 38], 7))
Output
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.

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.

First index with value >= 8 (lower bound)
3
0
↑lo
5
1
8
2
8
3
↑mid
8
4
11
5
14
6
test = nums[i] >= 8

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.

1/4
Python
def first_true(lo, hi, test): """Smallest x in [lo, hi) with test(x) true, or hi if none.""" while lo < hi: mid = (lo + hi) // 2 if test(mid): hi = mid # mid might be the answer: keep it else: lo = mid + 1 # mid is definitely not: skip it return lo nums = [3, 5, 8, 8, 8, 11, 14]first = first_true(0, len(nums), lambda i: nums[i] >= 8)last = first_true(0, len(nums), lambda i: nums[i] > 8) - 1print(first, last)
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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).

Koko: piles [3, 6, 7, 11], h = 8. Smallest speed that fits?
no
0
↑lo
no
1
no
2
yes
3
yes
4
yes
5
↑mid
yes
6
yes
7
yes
8
yes
9
yes
10
↑hi
speeds = 1..11

Index i means speed i + 1. Speed 6 needs 1 + 1 + 2 + 2 = 6 hours, which fits in 8. Keep it: hi = mid.

1/4
Python
def ship_within_days(weights, days): def feasible(capacity): used, load = 1, 0 for w in weights: if load + w > capacity: used += 1 load = 0 load += w return used <= days lo, hi = max(weights), sum(weights) # every possible answer while lo < hi: mid = (lo + hi) // 2 if feasible(mid): hi = mid else: lo = mid + 1 return lo print(ship_within_days([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))
Output
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.

Quick check
In Capacity To Ship Packages, why does the search start at max(weights) instead of 1?
Need a nudge? A hint rules out a wrong answer.

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.

Find the minimum of [4, 5, 6, 7, 0, 1, 2]
4
0
↑lo
5
1
6
2
7
3
↑mid
0
4
1
5
2
6
↑hi

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.

1/4
Python
def search_rotated(nums, target): lo, hi = 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[lo] <= nums[mid]: # left half is sorted if nums[lo] <= target < nums[mid]: hi = mid - 1 else: lo = mid + 1 else: # right half is sorted if nums[mid] < target <= nums[hi]: lo = mid + 1 else: hi = mid - 1 return -1 print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))print(search_rotated([4, 5, 6, 7, 0, 1, 2], 3))
Output
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.

Find a peak by walking uphill
1
0
↑lo
3
1
5
2
7
3
↑mid
6
4
4
5
2
6
↑hi

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.

1/4
Python
def find_peak(nums): lo, hi = 0, len(nums) - 1 while lo < hi: mid = (lo + hi) // 2 if nums[mid] < nums[mid + 1]: # uphill to the right lo = mid + 1 else: # mid or left holds a peak hi = mid return lo print(find_peak([1, 3, 5, 7, 6, 4, 2]))print(find_peak([5, 4, 3, 2, 1]))
Output
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.

Staircase search for 14
c0c1c2c3
r014711
r125812
r236916
r310131417

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.

1/5
Python
def search_flat(matrix, target): """Rows continue each other: treat the grid as one sorted list.""" rows, cols = len(matrix), len(matrix[0]) lo, hi = 0, rows * cols - 1 while lo <= hi: mid = (lo + hi) // 2 value = matrix[mid // cols][mid % cols] if value == target: return True if value < target: lo = mid + 1 else: hi = mid - 1 return False def search_staircase(matrix, target): """Rows and columns sorted separately: walk from the top-right.""" row, col = 0, len(matrix[0]) - 1 while row < len(matrix) and col >= 0: value = matrix[row][col] if value == target: return True if value > target: col -= 1 else: row += 1 return False print(search_flat([[1, 3, 5], [7, 9, 11]], 9))print(search_staircase([[1, 4, 7], [2, 5, 8], [3, 6, 9]], 6))
Output
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 it in order5 steps

Put the questions in the order you should ask them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each problem to its sub-pattern.

Choose an item, then its match on the other side.

Traps

  • Mixing loop styles. A closed range [lo, hi] goes with while lo <= hi and hi = mid - 1. A half-open range [lo, hi) goes with while lo < hi and hi = 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 = mid on a yes and mid = (lo + hi) // 2, a range like [4, 5] keeps picking 4 forever. When you move lo = 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) / 2 overflows near 2^31; write lo + (hi - lo) / 2. Python ints never overflow, and JS numbers are exact up to 2^53, but products like mid * mid still 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.

Quick check
This loop finds the last index with 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 - 1
Need a nudge? A hint rules out a wrong answer.

How 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."

Key terms
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.