Free beta: 60 days of full access, no card needed.84 seats leftSign up free

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy

All patterns

Binary search (array)

O(log n)

Look at the middle of a sorted range and throw away the half that cannot hold the answer. Repeat until one item is left.

Updated Oct 17, 2026

How does Binary search (array) work?

Keep two bounds, low and high, over the sorted range. The answer, if any, lies between them.

Take the middle index of that range. Compare the value there against the target.

On a match the search is over. Return that index.

If the middle value is too small, the target lies to the right. Move low past the middle.

If it is too large, move high below the middle. Half the range disappears either way.

The loop ends when low passes high. The range is empty, so the target is absent.

Sources: Wikipedia: Binary search, Python docs: bisect

  1. lo=0 hi=5Looking for 7 in [1, 3, 5, 7, 9, 11]. Six candidates.
  2. mid=2, value 55 is smaller than 7. Everything left of it is out.
  3. lo=3 hi=5, mid=4, value 99 is larger than 7. Everything right of it is out.
  4. lo=3 hi=3, mid=3, value 7One candidate is left, and it matches.
  5. return 3Three comparisons for six elements. Doubling the input adds one.
Find 13 in a sorted array by halving the range
binarySearch([1, 3, 5, 7, 9, 11, 13, 15], 13)
arr (sorted)
1
3
5
7
9
11
13
15

lo

hi
target = 13lo = 0hi = 7mid = -return = ?

Find 13 in a sorted array. lo and hi mark the range where it can still be: at first, the whole array.

Speed race
Binary search against a linear scan over the same 48 sorted numbers

Bars: the sorted numbers. Binary search halves the range at every comparison; the scan reads them one by one.

One operation is one comparison with the target. Every frame, each lane does the same number of operations, so the slow one falls behind.

Linear scan O(n)
0 operations
Binary search O(log n)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Linear scan900 · under 1 ms
Binary search10 · under 1 ms
n = 100,000
Linear scan90K · under 1 ms
Binary search16.6 · under 1 ms
n = 10,000,000
Linear scan9M · 90 ms
Binary search23.3 · under 1 ms

The Binary search (array) code template

function binarySearch(arr, target) {
    let lo = 0, hi = arr.length - 1;
    while (lo <= hi) {
        const mid = (lo + hi) >> 1;
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

A worked example of Binary search (array)

First and last position of a value

A sorted array can hold the same value many times over. Return the first and last index of a target.

If the value is missing, return minus one twice.

Run the search twice with a different tie-break.

For the first index, keep pushing high left after a match. For the last, keep pushing low right.

function searchRange(nums, target) {
    function bound(findFirst) {
        let lo = 0;
        let hi = nums.length - 1;
        let found = -1;

        while (lo <= hi) {
            const mid = lo + Math.floor((hi - lo) / 2); // cannot overflow

            if (nums[mid] === target) {
                found = mid;
                // a match is not the end: keep squeezing the chosen side
                if (findFirst) hi = mid - 1;
                else lo = mid + 1;
            } else if (nums[mid] < target) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        return found;
    }

    return [bound(true), bound(false)];
}

When should you use Binary search (array)?

Use Binary search (array) when the problem statement says “sorted array”, “find a target / first or last occurrence” or “n up to 1e6+ and O(log n) expected”. A solution built on it usually runs in O(log n).

  • sorted array
  • find a target / first or last occurrence
  • n up to 1e6+ and O(log n) expected
  • find the boundary where a condition flips
  • search a rotated-but-mostly-sorted array (with a twist)

The signal words of every pattern sit in one table, the algorithm patterns cheat sheet.

What is Binary search (array) confused with?

Binary search (array) is most often confused with Linear search, Binary search on a rotated array, Binary search on the answer, Binary search tree and Two pointers (opposite ends).

Common mistakes with Binary search (array)

  • Computing mid as lo plus hi over two

    That sum can pass the safe integer range. Write lo plus half of the gap.

  • Moving a bound to mid instead of past it

    The range stops shrinking and the loop never ends. Use mid plus one or mid minus one.

  • Mixing the two loop shapes

    With lo <= hi both ends are inclusive. Changing one end alone breaks the invariant.

  • Searching data that is not sorted

    The comparison assumes everything left of mid is smaller. Without that the answer is silently wrong.

Interview problems solved with Binary search (array) include Binary search, Search insert position, First and last position of an element, Find peak element, Sqrt of x, Search a 2D matrix and Smallest letter greater than target.

  • Binary search: The plain form over distinct sorted values.
  • Search insert position: Return where the value would belong if it is missing.
  • First and last position of an element: Two searches with opposite tie-breaks.
  • Find peak element: Compare against the neighbour instead of a target.
  • Sqrt of x: The sorted range is the set of answers, not an array.
  • Search a 2D matrix: Treat the whole grid as one sorted list.
  • Smallest letter greater than target: An upper bound that wraps back to the start.

What is the time and space complexity of Binary search (array)?

The target complexity of Binary search (array) is O(log n).

n up to 1e9 is fine, because log2 of 1e9 is about 30. Time is O(log n), space is O(1).

Open the free lesson on this pattern