TheScalableDev
AlgorithmsBeginner25 minO(log n) time · O(1) spaceFree

Binary Search

Status

Halve the search space every step. Trace low, mid, and high as they converge on the target.

BestO(1)AverageO(log n)WorstO(log n)SpaceO(1)

You are searching a paper dictionary, not by flipping every page, but by opening it in the middle. If the word comes before that page, the entire second half is now irrelevant - throw it away. Each guess cuts what is left in half, so even a million entries costs you only about twenty page-flips.

Builds on

  • Logarithms — the worst-case count is floor(log2 n) + 1, so you need to know that log2 of 1,000,000 is about 19.93.
  • Big-O notation — the O(log n) bound and the O(1) space claim both rest on counting halvings and variables.
01

What is binary search?

binary search answers one question: is the target in this sorted array, and at which index? It looks at the middle element first. Because the array is sorted, one comparison tells you which half could still contain the target, and the other half can be discarded without being read.

MethodValues checkedProbesNeeds sorted input?
Linear scan2, 5, 8, 12, 165no
binary search23, 8, 12, 164yes
Finding 16 in the 11-item example array

Check yourself

Which statement about binary search is true?

02

Where it shows up

Anywhere data is kept in sorted order, a lookup can halve: a sorted index in a database, the sorted keys inside each node of a B-tree, a commit history searched by git bisect, and a sorted list of timestamps searched for the version live at time T. binary search is also the building block for searches over a condition, where the search space is a range of candidate values instead of a stored array.

Check yourself

Which task is NOT a binary search over sorted data?

03

The intuition

halve each step

Guess the middle. If nums[mid] is smaller than the target, every index up to mid holds a value that is smaller still, so the left side can be discarded. If nums[mid] is larger, the right side can be discarded. Either way mid itself is discarded too, because it was just checked.

Check yourself

You probe mid and find nums[mid] = 40, while the target is 25. Which part of the range can be discarded?

04

Complexity

O(log n)

Each probe removes mid and everything on one side, so the candidate range roughly halves each time. The worst case ends with a single element that still needs one more comparison, so the count is floor(log2 n) + 1 rather than log2 n. Counts below are the largest number of probes over every possible target, both present and absent.

worst comparisons = floor(log2 n) + 1 → 7 → 3 · 1,000 → 10 · 1,000,000 → 20
Each probe discards half the remaining items, plus one final check.
nlog2 nfloor(log2 n) + 1Worst case, checked in node
72.8133
1,0009.971010
1,02410.001111
1,000,00019.932020
Run it in node: the worst case over every target, for each size
1function searchWithCount(nums, target) {
2 let low = 0, high = nums.length - 1, probes = 0;
3 while (low <= high) {
4 const mid = Math.floor((low + high) / 2);
5 probes++;
6 if (nums[mid] === target) return { index: mid, probes };
7 if (nums[mid] < target) low = mid + 1;
8 else high = mid - 1;
9 }
10 return { index: -1, probes };
11}
12
13function worstCase(n) {
14 const nums = Array.from({ length: n }, (_, i) => i * 2);
15 let worst = 0;
16 for (let t = -1; t <= 2 * n; t++) worst = Math.max(worst, searchWithCount(nums, t).probes);
17 return worst;
18}
19
20for (const n of [7, 1000, 1000000]) {
21 console.log(n, worstCase(n), Math.floor(Math.log2(n)) + 1);
22}

Check yourself

What is the worst-case number of comparisons for 1,024 sorted items?

05

The loop invariant

A loop invariant is a claim that stays true at every iteration. Here it is: if the target is in the array, its index lies inside [low, high]. Check it at three moments and the algorithm's correctness follows.

MomentWhat holdsWhy
Startlow = 0 and high = n - 1, so the range covers every indexThe whole array is the search space before any probe
Each iterationThe target, if present, stays inside [low, high]nums[mid] is not the target, and the array is sorted, so the discarded half cannot hold it
ExitThe range is empty (low > high)No index is left to hold the target, so the function returns -1

Termination is part of correctness. Every iteration either returns or moves low or high past mid, so the range shrinks by at least one item each time and the loop must end. Moving low to mid instead of mid + 1 would break that shrink step.

Check yourself

Which statement is the loop invariant of this search?

06

One hard rule

The discard step depends on order: when nums[mid] is too large, everything to its right is also too large. Without sorted order that inference fails, and the loop can discard the very half that holds the target. The function does not raise an error; it returns a wrong -1.

Check yourself

Search [1, 3, 2] for 2 with this loop. What does it return?

07

Exact match versus a condition

The loop here is an exact-match search: it stops as soon as nums[mid] equals the target. With duplicates it returns whichever matching index is probed first, which need not be the leftmost one. Searches that ask for the first index where a condition becomes true are a different template, with their own choice between lo < hi and lo <= hi. That template is taught in binary search on the answer and is not repeated here.

Question askedReturnsTemplate
Is 16 in this sorted array, and where?index 4, or -1exact match (this lesson)
Where is the first value at least 10?index of the first qualifying valuefirst-true (pattern lesson)
What is the smallest capacity that passes a check?the smallest passing valuesearch over the answer (pattern lesson)

Check yourself

Search [1, 4, 4, 4, 9] for 4 with the exact-match loop. Which index is returned?

08

Edge cases

The target may be missing, duplicated, or at either end. A correct implementation handles all three: a missing target leaves the range empty and returns -1, a duplicate returns some matching index, and both ends are reached because the loop tests low <= high rather than low < high.

Check yourself

When does the loop end without finding the target?

09

Midpoint overflow and JavaScript

The naive midpoint (low + high) / 2 forms a sum first. In a fixed-width integer that sum can overflow and wrap to a wrong value. JavaScript is different: every number is a double, which is exact for every integer up to 2^53 - 1 = 9,007,199,254,740,991. The largest possible array index is 2^32 - 2, so the largest sum is about 8.6 billion, far inside that limit. In JavaScript the naive midpoint is exact for any array.

LanguageInteger typeIs (low + high) / 2 safe?
JavaScriptdouble, exact up to 2^53 - 1yes, for every possible array index
Java or C with a 32-bit int32-bit signed, maximum 2,147,483,647no, once low + high passes 2^31 - 1, which needs indices near 2^30 (a billion)

Write low + Math.floor((high - low) / 2) anyway. It reads as 'the middle of the gap', and it is the form that transfers safely to Java and C.

Check yourself

What is the largest safe integer in JavaScript, meaning every integer up to it is exact?

10

Interview script

  1. 01Restate (1 min)

    Confirm the input is sorted and what to return on a miss, usually -1.

  2. 02Brute force (1 min)

    A linear scan checks up to n values; for a million sorted items that is up to a million comparisons.

  3. 03Insight (2 min)

    sorted order means one comparison discards half the remaining range.

  4. 04Code (5 min)

    Set low and high, compute mid, compare, move low or high past mid, and loop while low <= high.

  5. 05Cost (2 min)

    O(log n) time and O(1) space. Worst case is floor(log2 n) + 1 comparisons: 20 for a million items.

  6. 06Edges (1 min)

    Empty array, missing target, duplicates, and the midpoint in a fixed-width language.

Recap

  • binary search finds a target in a sorted array by halving the range each step.

  • The data must be sorted. On an unsorted array the loop can return -1 for a value that is present.

  • Worst-case comparisons are floor(log2 n) + 1: 7 items take 3, 1,000 take 10, and 1,000,000 take 20.

  • The loop invariant: if the target is present, it lies inside [low, high]. An empty range (low > high) means the target is absent.

  • Use low + Math.floor((high - low) / 2) for the midpoint. JavaScript doubles are exact to 2^53 - 1, but 32-bit integers overflow.

  • First and last occurrences, and searches over a condition, use the templates in the pattern lesson.

Terms in this lesson

Every acronym and concept, expanded. Tap a term to open it.

time complexity

How an algorithm's number of operations grows with input size.

data structure

A way of organizing data in memory (array, tree, map) that determines which operations are fast.

binary search

Halving a sorted search space each step to find a value in O(log n).

linked list

A chain of nodes where each points to the next, giving cheap inserts and deletes but O(n) access.

call stack

The stack of active function calls the runtime tracks; each recursive call adds a frame.

algorithm

A precise, step-by-step procedure that solves a problem.

invariant

A statement that stays true before and after every loop iteration. Here: if the target is present, its index lies in [low, high].

latency

The time a single request takes from start to finish.

array

A contiguous block of memory holding items in order, readable by index in O(1).

stack

A last-in-first-out structure: you push on top and pop from the top.

node

One element in a linked structure, holding a value and pointers to its neighbors.

tree

A hierarchy of nodes where each node has one parent and zero or more children.

bit

A single 0 or 1 - the smallest unit of data.

sorted

Ordered smallest to largest - the one hard requirement binary search cannot work without.

halving

Cutting the search range in half at each step; the reason the algorithm is O(log n).

probe

One comparison of nums[mid] against the target. The worst-case cost is counted in probes.

midpoint

The middle index, computed as low + Math.floor((high - low) / 2) so the sum low + high is never formed.

logarithmic

Growing with the number of times you can halve n - log2(1,048,576) is 20.

integer overflow

When a sum such as low + high exceeds the largest value a fixed-width integer can hold, and wraps around to a wrong result.

double

The only number type in JavaScript: a 64-bit floating-point value, exact for every integer up to 2^53 - 1.

JSJavaScript

The language of this lesson's code samples. Its numbers are doubles, which is why the midpoint sum is exact here.

Where you will see it

Real systems that use this exact idea. Tap a card to open it.

Common traps

The mistakes interviewers watch for. Guess the fix, then reveal it.

  1. FixUse low <= high. With strict <, a single-element range [i, i] never gets checked and targets at the last position are missed.

  2. FixAlways move past mid: low = mid + 1 or high = mid - 1. Keeping mid in the range can stall the loop when the range narrows to two elements.

  3. FixInteger overflow when low + high exceeds 2^31 - 1 in a 32-bit int. Use low + (high - low) / 2. This bug has appeared in widely used library code, so treat the naive form as a known trap.

  4. FixThe shift truncates the sum to 32 bits, so past 2^31 - 1 the result is wrong: (2^31 + 2^31) >> 1 returns 0. Use Math.floor((low + high) / 2).

Interview prep

Questions you could be asked, with the depth an interviewer wants to hear.

Only on sorted data. If the input is not sorted, the discard-half logic is invalid and the result is wrong.

O(log n) · requires sorted data

Real worldDatabase indexes and git bisect both rely on this precondition.

DeeperIf you need binary search on unsorted data, you pay the sort cost first.