Skip to content

Pattern · Interview prep

Binary Search

Cut a sorted range in half. The middle value tells you which side can still hold the answer, so the other side is discarded.

What it is

What is the binary search pattern?

Binary search keeps two bounds around the range that might still hold the answer. Each step reads the middle. If that value is too small, the answer is to the right. If it is too large, the answer is to the left. Half of the remaining indexes disappear on every comparison.

  • Exact match. Stop when the middle equals the target. If the bounds cross, the target is absent.
  • Boundary. Keep the first index where the value is at least the target. That index is where a new value would be inserted.
  • Search the answer. The array is the set of answers you might try, from too small to large enough. A check says whether this answer works. The search finds the smallest one that does.
Sorted row, target 7
target7

Middle is 5, below 7, so the low end moves past it

LLowRHigh

When to use it

How do you recognize a binary search problem?

Read the statement for these signals before you scan from the left.

Read the full recognition guide: Binary search beyond sorted arrays: searching the answer

Phrases to watch for

  • sorted
  • find the index
  • insertion index
  • first position
  • rotated but still ordered
  • minimize the maximum
  • a larger answer stays valid
  1. 1

    The data is sorted, or the answers are ordered

    Values increase, or “too small” comes before “large enough.” The middle comparison has a direction.

  2. 2

    You need a boundary, not every match

    One index is enough: the target, the insert point, or the smallest answer that passes a check.

  3. 3

    A check gets stricter as the candidate grows

    If this capacity works, every larger one works. If it fails, every smaller one fails. That is the permission to discard a half.

Looks similar, but isn’t

  • You want a pair and both ends move one step

    Two Pointers walks inward. Binary search jumps to the middle and drops a whole side.

  • The list is not ordered

    A middle value then says nothing about the other half. Remember the complement in a Hash Map.

  • You need every prefix, not one boundary

    Prefix Sum stores a total at each index. Searching those totals is a later step, and only when they are ordered.

Worked example

How does it work on a lookup in a sorted list?

The integers are distinct and sorted in increasing order. Return the index of the target, or -1 if it is absent. Each comparison should discard half of the remaining range. This is exact search, and one of the problems you can practice below.

TypeScriptindexOfTarget
function indexOfTarget(nums: number[], target: number): number {  let low = 0;  let high = nums.length - 1;   while (low <= high) {    const mid = low + Math.floor((high - low) / 2);    const value = nums[mid];     if (value === target) return mid;    if (value < target) low = mid + 1;    else high = mid - 1;  }   return -1;}

One comparison discards one half.

Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.

Complexity

  • TimeO(log n)

    Each step halves the range between low and high.

  • SpaceO(1)

    Only the two bounds and the middle index are stored.

The insert index

Stop when low passes high. low is then the first index whose value is at least the target, or the length of the row if every value is smaller. An empty row returns 0.

Searching the answer

For the lightest legal load, the search is over capacities, not packages. The low bound is the heaviest package. The high bound is the sum of every package. A capacity works when the packages ship in the allowed number of days.

Step by step on [1, 3, 5, 7, 9] with target 7

  1. 1

    low is 0 and high is 4. The middle index is 2, and the value is 5. 5 is below 7, so low becomes 3.

  2. 2

    The range is indexes 3 and 4. The middle is 3, and the value is 7. Return 3.

Common mistakes

What mistakes do people make with binary search?

  • Bounds that never shrink

    Setting `low = mid` when the middle is too small leaves the same range in place. The loop never ends.

    InsteadMove past the middle: `low = mid + 1` or `high = mid - 1`. The side you keep must be strictly smaller.

  • Returning “not found” when the problem wants the insert point

    A missing value still has a place on a sorted shelf. `-1` is the wrong answer when the caller needs that place.

    InsteadDecide up front whether you return the match or the first index where the value would go. They are different loops.

  • Searching data that is not ordered

    If the middle is smaller than the target, the right side is not guaranteed to hold it. Half the range was discarded on a false lead.

    InsteadSort first, or use a Hash Map. Binary search needs a direction at the middle.

  • Letting the middle index fall outside the bounds

    A midpoint written as a wide sum can land past the array, or skip the last remaining index.

    InsteadUse `low + Math.floor((high - low) / 2)`. Check `low <= high` so a one-element range is still examined.

Practice it in Algofily

Which Algofily problems train binary search?

5 problems are tagged Binary Search. They run from an insert index on a sorted shelf to the smallest capacity that still finishes on time.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.