Learn / Binary search

Binary search on sorted arrays

When data is sorted, one look at the middle tells you which half cannot hold the answer. Throw that half away and repeat: about log₂ n looks instead of n. Most problems here are one question in disguise: where is the first index where a yes/no test turns from no to yes?

How to recognise it

  • The array is sorted (or sorted by some key), and n is large enough that O(n) per query is too slow.
  • The question asks for the first or last position of something, a count of equal values, or where a value would be inserted.
  • Each index answers a yes/no test, and all the "no" answers come before all the "yes" answers.
  • The array is not sorted, but comparing a middle value with its neighbour still tells you which side to keep (as in Find Peak Element).

The idea in one picture

Guess a number from 1 to 100 when the only hint is "higher" or "lower". The best first guess is 50, because whatever the reply, half the numbers are gone. Binary search does exactly that on a sorted array: look at the middle, keep the half that can still hold the answer, repeat.

The yes/no view

Most binary search problems can be turned into one question. Write a test that every index answers with no or yes, so that all the no answers come first:

index012345
nums133589
test: nums[i] ≥ 4nononoyesyesyes

The answer is the first yes, index 3. Lower bound, upper bound, insert position, first and last position and counting are all this one search with a different test.

Lower bound: the template behind most of them

lo = 0, hi = n                 # the answer is somewhere in lo..hi; n means "no yes at all"
while lo < hi:
    mid = lo + (hi - lo) / 2
    if test(mid): hi = mid     # mid is a yes: the first yes is mid or to its left
    else: lo = mid + 1         # mid is a no: the first yes is to its right
return lo

When the loop ends, lo equals hi and points at the first yes, or at n if there is none.

ProblemTest
Lower bound, Search Insert Positionnums[i] ≥ x
Upper boundnums[i] > x
First and last positionlower bound of x, and upper bound of x minus 1
Count occurrencesupper bound minus lower bound
Single element in a sorted arrayat an even index i, nums[i] ≠ nums[i + 1]

Exact match: the classic template

When you only need "is it there, and where", the classic form stops as soon as it finds the value:

lo = 0, hi = n - 1
while lo <= hi:
    mid = lo + (hi - lo) / 2
    if nums[mid] == target: return mid
    if nums[mid] < target: lo = mid + 1
    else: hi = mid - 1
return -1

Do not mix the two forms. lo < hi goes with hi = mid, and lo <= hi goes with hi = mid - 1.

Common mistakes

  • Mixing the templates, as in while lo <= hi with hi = mid, which can loop forever.
  • Starting hi at n - 1 in the lower-bound template, so "every value is too small" can never be answered.
  • Writing (lo + hi) / 2 in Java or C++ where both can be large.
  • Using < in the test when the question needs ≤, which finds the wrong end of a run of equal values.

Problems

0 of 12 solved

Check yourself

An array has 1,000,000 sorted values. About how many middle checks does binary search need in the worst case?

In the template "while lo < hi, if test(mid) then hi = mid else lo = mid + 1", why does the loop always end?

For nums = [1, 2, 2, 2, 5], what are the lower bound and the upper bound of 2?

Why write mid = lo + (hi - lo) / 2 instead of (lo + hi) / 2 in Java or C++?

In Find Peak Element, nums[mid] < nums[mid + 1]. Which side surely contains a peak?