Algorithm patterns← All patterns

Pattern 03 / 10 · Fundamentals

Binary Search

Halve the search space every step until only the answer is left.

The idea

Keep a range [lo, hi] that must contain the answer. Look at the middle: it either is the answer, or it proves the whole left or right half can be thrown away. The range halves every step.

time O(log n)space O(1)

Reach for it when

  • The data is sorted, or the answer space is monotonic (false… false, true… true).
  • You need O(log n) instead of a linear scan.
  • The problem asks for the first or last position where something becomes true.

Watch it run

704. Binary Search

Return the index of target in a sorted array, or -1 if it is not there.

Example 1

Input: nums = [-1, 0, 3, 5, 9, 12], target = 9

Output: 4

Explanation: 9 exists in nums and its index is 4.

Example 2

Input: nums = [-1, 0, 3, 5, 9, 12], target = 2

Output: -1

Explanation: 2 does not exist in nums so return -1.

WALKTHROUGH INPUT · nums = [-1, 0, 3, 5, 9, 12, 15, 20], target = 12

lo
-1
0
0
1
3
2
5
3
9
4
12
5
15
6
hi
20
7
target = 12range size = 8

The answer, if it exists, is somewhere in [0, 7].

1 / 5
solution.ts
1function search(nums: number[], target: number): number {
2 let lo = 0, hi = nums.length - 1;
3 while (lo <= hi) {
4 const mid = Math.floor((lo + hi) / 2);
5 if (nums[mid] === target) return mid;
6 if (nums[mid] < target) lo = mid + 1;
7 else hi = mid - 1;
8 }
9 return -1;
10}

Practice next