Skip to content
{}

Lesson 15

Binary Search: Halve and Conquer

Find anything among a billion sorted items in about 30 guesses.

18 min

01Why it matters & the intuition

Binary search is the purest O(log n) algorithm and a pattern far beyond sorted arrays — 'binary search on the answer' solves scheduling, capacity and optimisation problems.

Think of it like…

The number-guessing game: 'I'm thinking of a number from 1 to 100.' Guess 50. 'Higher.' Guess 75. Each answer throws away half the remaining numbers.

02See it move

Press play, then step through slowly. Change the input and predict the next frame before you click.

Binary search
interactive
Try a missing value like 50 — or the first/last element.
1/7
0
3
lo
1
8
2
12
3
17
4
21
5
26
6
30
7
34
8
41
9
47
10
52
11
58
12
63
13
71
14
79
15
88
hi
›Search for 47. The whole array is in play.
  • mid
  • found

03Key ideas

Invariant

If the target exists, it is always inside [lo, hi]. Every step must shrink the range while keeping that promise.

Avoid overflow

Use lo + Math.floor((hi - lo) / 2). In languages with fixed-width ints, (lo + hi) / 2 can overflow.

Lower bound

The first index where arr[i] >= target — also the insertion point. Most off-by-one bugs disappear once you think in lower bounds.

Search the answer space

If a yes/no check is monotonic (false…false, true…true), binary search finds the boundary without any array at all.

04Build it from scratch

A clean reference implementation. Read it line by line — then close it and write your own in the lab below.

typescript
function binarySearch(arr: number[], target: number): number {
  let lo = 0;
  let hi = arr.length - 1;
  while (lo <= hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) lo = mid + 1; // discard left half
    else hi = mid - 1;                     // discard right half
  }
  return -1;
}

// First index i with arr[i] >= target (arr.length if none).
function lowerBound(arr: number[], target: number): number {
  let lo = 0;
  let hi = arr.length; // half-open [lo, hi)
  while (lo < hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

05Complexity

OperationTimeSpace
Search sorted arrayO(log n)O(1)
Lower / upper boundO(log n)—
Requiressorted input (or monotonic predicate)—

06Check your understanding

Question 1

Q1.Max comparisons to binary-search 1,024 sorted items?

Question 2

Q2.Binary search on an unsorted array…

Question 3

Q3.while (lo <= hi) with hi = arr.length - 1 searches…

07Code lab

Write Python(or switch to JavaScript) and run it against real test cases. Python runs inside your browser — nothing is uploaded — and a C++ reference solution is under “Solution”.

Search insert position

Write search_insert(nums, target) for a sorted array of distinct numbers. Return the index of target if found, otherwise the index where it would be inserted to keep order. Must be O(log n).

function: search_insertPython starts when you get here