DSAIntermediate7 min readPart 5 of 16

Binary Search

Binary search finds a target in a sorted array by halving the search space on every step. It turns an O(n) scan into an O(log n) lookup: about 20 steps for a million elements.

Can you explain binary search out loud?

I'm Alex. Read this, then I'll interview you on real problems and push on the parts you skip.

How binary search worksHow it works

Keep two pointers, left and right, around the part of the array that could still hold the target. Look at the middle element. If it matches, you are done. If the target is smaller, throw away the right half; if it is bigger, throw away the left half. Repeat until the range is empty.

Find 23 in a sorted array

258121623385672910123456789LmidR16 < 23, so the answer is to the right: L = mid + 1thrown away258121623385672910123456789LmidR56 > 23, so the answer is to the left: R = mid − 1258121623385672910123456789midFound 23 in 3 steps instead of 6.
WalkthroughEach step halves what is left, so n elements take about log₂ n steps.
Binary searchTypeScript
function binarySearch(nums: number[], target: number): number {
  let left = 0, right = nums.length - 1;
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (nums[mid] === target) return mid;
    else if (nums[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1; // not found
}
TimeO(log n)SpaceO(1)

Why left + (right − left) / 2?Core idea

(left + right) / 2 can overflow (go past the largest integer the language can store) when both are large. left + (right - left) / 2 gives the same middle but never adds two big numbers together.

Variation: first occurrencePattern

With duplicates, finding a match is not enough; you often need the first one. When you find the target, remember it and keep searching to the left.

133357012345first 3A match at index 2 is saved, then the search keepsgoing left to find index 1.
Find the first occurrenceTypeScript
function findFirst(nums: number[], target: number): number {
  let left = 0, right = nums.length - 1, result = -1;
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (nums[mid] === target) {
      result = mid;
      right = mid - 1; // keep searching left
    } else if (nums[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return result;
}

More variationsPattern

Search in a rotated arrayone half sorted

A sorted array rotated at some point, like [4, 5, 6, 7, 0, 1, 2]. One half around mid is always sorted: check which one, then decide which side can hold the target.

Binary search on the answermonotonic

When a yes/no check flips only once as the answer grows (for example, “can we ship all packages in D days with capacity C?”), binary search over possible answers instead of over the array.

Common mistakesPitfalls

Infinite loopSetting left = mid or right = mid when mid is not a match can stop the range from shrinking. Use mid + 1 and mid − 1.
Off-by-oneThe loop condition (<= or <) and the updates must match. With left <= right, use right = mid − 1.
Unsorted inputBinary search only works on sorted data (or a monotonic test). Check before you use it.
Integer overflowUse left + (right − left) / 2 instead of (left + right) / 2.
Skipping edge casesOne element, target smaller than everything, target bigger than everything.

In the interviewIn the interview

Stating the invariant (the rule that stays true every loop) is what makes your bounds easy to trust.

Frequently asked questionsFAQ

Why is the midpoint written as left + (right - left) / 2?

That form avoids integer overflow when left and right are very large indices. Computing (left + right) / 2 first can exceed the maximum representable integer and wrap to a negative value, producing a wrong midpoint. The subtraction form is mathematically identical but stays within range, so it is always safe to use regardless of index size.

What is binary search on the answer and when is it used?

Binary search on the answer searches over a range of possible solutions instead of over array elements. It works when the answer space is monotonic: if a candidate value is feasible, larger values are feasible too, and if it is infeasible, smaller values are. You write a feasibility check, then binary search the smallest feasible value. Common cases include minimum shipping capacity and maximum minimum distance.

How do you find the first or last position of a value in a sorted array with duplicates?

On a match, do not return immediately. For the first occurrence, record the index and then narrow right to mid minus 1, continuing the search left. For the last occurrence, record the index and narrow left to mid plus 1, continuing right. Either way the loop keeps shrinking, so total time stays O(log n) even with many duplicates.

Now explain binary search to me out loud

I'll give you interview problems and ask follow-ups, like a real interviewer.

Practice with Alex

Keep readingKeep reading

Ready to practice?

Reading is step one. Saying it out loud is step two.

Start a mock interview with Alex, get pushed on the parts you skip, and see your hiring signal right after.