Level Up Your Coding Skills & Crack Interviews — Save up to 50% or more on Educative.io Today! Claim Discount

Arrow
Table of contents

Binary Search

Binary Search is one of the highest-ROI topics for coding interviews. It’s fast, elegant, and shows up frequently: searching in sorted arrays, finding boundaries, answer space problems, optimization, and even graphs/DP when you spot the right monotonic behavior.

At its core, Binary Search transforms a linear search, checking every single item, into a lightning-fast process that can find an element in a list of billions in just a few dozen steps. It achieves this by discarding half of the remaining search space at every step, using comparisons to decide which half can be ignored.

If you get comfortable with when binary search applies and how to write it without bugs, you’ll solve a big chunk of LeetCode efficiently and confidently.

The real-world intuition

Imagine you are looking for the word “Marmot” in a physical dictionary. As you know the word starts with the letter ‘M’, you don’t start your search with page 1 and flipping through the ‘A’s. You know the book is sorted alphabetically, so you use that structure to your advantage by starting much further in.

To begin, you open the dictionary roughly to the middle and check the words on that page. Let’s say you land on a section where the words start with “Me…”. You compare your target, “Ma”, to what you see on the page. As “Ma” comes before “Me” in the alphabet, you know with absolute certainty that “Marmot” must be located in the pages to your left.

At this point, you effectively discard the entire right half of the book from your search. You then take the remaining section of pages on the left, split them in the middle again, and repeat the same logic. By choosing a direction and eliminating half of the remaining search space at every single step, you find your target really quickly. This process is exactly how Binary Search works.

What is Binary Search?

Binary Search is a divide-and-conquer searching algorithm that finds a target value (or target position) in a sorted sequence by repeatedly comparing the target to the middle element and eliminating half of the remaining search range each step.

A crucial prerequisite:

For Binary Search to work, the data must be sorted, usually in ascending order. If the data is unsorted, you cannot reliably discard half of the elements because you don’t know where the target should be.

Why is Binary Search powerful?

FeatureLinear SearchBinary Search
Best use caseWorks on any list, including unsorted data.Works on sorted data.
How it worksChecks elements one by one from start to end.Repeatedly checks the middle element and discards half the search space.
SpeedSlow; time grows 1:1 with data.Incredibly fast; grows logarithmically.
Time complexity (average/worst)O(n)O(log n)

Which data structures works well with Binary Search?

Binary Search works best on data structures that provide sorted order and fast random access, so we can jump directly to the middle element.

  • Arrays/Dynamic Arrays (best fit): Works extremely well on arrays (and array-likes such as Python lists, Java arrays, C++ vectors) because you can access the middle element in O(1) time.
  • Sorted 2D Arrays/Matrices (common variation): Works when the matrix is sorted in a way that allows binary search, for example when each row is sorted and rows are ordered, or when you apply binary search per row.
  • Binary Search Trees (BSTs): BSTs are conceptually “binary search” structures because left < root < right, but searching in a BST is not the binary search algorithm on an array. Also, in an unbalanced BST, search can degrade to O(n).

Does Binary Search work with Linked Lists?

No. Even if a linked list is sorted, accessing the middle element takes O(n) time (you must traverse), so using binary search loses its advantage and typically becomes inefficient.

How does Binary Search work?

Binary Search maintains a shrinking window of where the answer could still be using two pointers:

  • low: Initialized at the start of the search range.
  • high: Initialized at the end of the search range

The main steps of the Binary Search are as follows:

  1. Compute the midpoint as mid = low + (high – low) // 2.
  2. Compare the value pointed by the mid with the target value:
    1. If both are equal, return the mid.
    2. If the value at mid < target, the target must be in the right half, so move the low pointer forward low = mid + 1.
    3. If the value at mid > target, the target must be in the left half, so move the high pointer backward high = mid – 1.
  3. Repeat until the window is empty, i.e., low > high.

Why use (low + (high – low) / 2) instead of ((low + high) / 2) to compute the mid?

In many programming languages, adding two large integers can cause an integer overflow. The subtraction method is mathematically identical but safer.

Let’s look at the following illustration to get a better understanding of the Binary Search algorithm:

1 / 5

Binary Search template in Python (interview-ready)

In interviews, it helps to memorize a clean, reusable template. Here is the classic exact match template (works when the array is sorted and you want the index of the target):

Complexity analysis for Binary Search

  • Time complexity (O(log n): Each iteration of binary search cuts the search space in half, so the number of comparisons grows logarithmically with the size of the input.
  • Space complexity O(1): The iterative implementation uses only a constant amount of extra memory, relying on a few pointers (low, high, and mid) regardless of input size.

How fast is O(log n)?

If you have 1,000,000 elements:

  • Linear Search: Might take 1,000,000 checks.
  • Binary Search: Takes at most 20 checks (log21,000,00020\log_2 1,000,000 \approx 20log2​1,000,000≈20).

Modified Binary Search

In many coding interview problems, the input is not a perfectly sorted array. Instead, it has some structure that still lets you discard half the search space. This is where Modified Binary Search comes in: you keep the binary search framework, but tweak the “which half to discard?” logic based on the problem’s structure.

Classic example: Search in Rotated Sorted Array

A classic example is LeetCode 33 (Search in Rotated Sorted Array), where you search for a target in a rotated sorted array (the array is sorted but then rotated at an unknown pivot), such as:

nums = [4, 5, 6, 7, 0, 1, 2]

Even though it’s rotated, one important fact remains true: At least one half (left or right) is still sorted in every iteration.

So, instead of directly deciding which side to search in, left or right, based only on nums[mid] and target, we first identify the sorted half and use that to guide the search.

Step by step solution

  1. Start with the full range of the array and compute the middle index. If nums[mid] equals the target, return mid.
  2. Next, determine which half is sorted:
    1. If nums[low] <= nums[mid], the left half (low..mid) is sorted. Check whether the target lies within this sorted range (nums[low] <= target < nums[mid]).
      1. If yes, move left (high = mid - 1).
      2. If no, move right (low = mid + 1).
    2. Otherwise, the right half (mid..high) is sorted. Check whether the target lies within this sorted range (nums[mid] < target <= nums[high]).
      1. If yes, move right (low = mid + 1).
      2. If no, move left (high = mid - 1).
  3. Repeat until the search range becomes invalid (low > high). If the target is not found, return -1.

This keeps the same binary search framework, but modifies the decision step to account for rotation, hence Modified Binary Search.

Python implementation

Now, let’s look at the optimized solution code for Search in Rotated Sorted Array.

Common Binary Search use cases

Binary Search appears in many forms across coding interviews, often hidden behind different problem statements. Recognizing these common use cases helps you quickly identify when binary search is the right tool and apply the correct pattern with confidence.

Use caseWhat you practiceCommon LeetCode problems
Classic exact searchFind an element in a sorted arrayBinary Search (704), Search Insert Position (35)
Lower/Upper Bound (boundaries)First index >= target, first index > target, duplicates handlingFind First and Last Position of Element in Sorted Array (34)
Insert position / first greaterWhere a value should be inserted to keep array sortedSearch Insert Position (35), Find Smallest Letter Greater Than Target (744)
Peak / local optimumBinary search on index using neighbor comparisonsFind Peak Element (162), Peak Index in a Mountain Array (852)
Rotated sorted arrayIdentify sorted half, pivot logicSearch in Rotated Sorted Array (33), Find Minimum in Rotated Sorted Array (153), Search in Rotated Sorted Array II (81)
Single element in pairsUse parity + binary search to find odd one outSingle Element in a Sorted Array (540)
2D matrix searchTreat matrix as sorted 1D or do row-based binary searchSearch a 2D Matrix (74), Search a 2D Matrix II (240)
Binary Search on Answer (min feasible)Search smallest value that satisfies a monotonic conditionKoko Eating Bananas (875), Capacity To Ship Packages Within D Days (1011), Minimum Days to Make m Bouquets (1482), Find the Smallest Divisor Given a Threshold (1283)
Binary Search on Answer (min/max optimization)Minimize maximum / maximize minimum with feasibility checksSplit Array Largest Sum (410), Magnetic Force Between Two Balls (1552)
Median / partition (advanced)Binary search on partition rather than valuesMedian of Two Sorted Arrays (4)

Frequently Asked Questions

What are the types of Binary Search?

The two main types are iterative binary search and recursive binary search.

What are the best-case and worst-case scenarios for Binary Search?

The best-case scenario occurs when the middle element of the very first check is the target value; this results in a time complexity of O(1). The Worst-Case scenario occurs when the target is at the very ends of the array or not in the list at all, requiring log2(n) comparisons, which is O(log n).

Is iterative or recursive Binary Search better?

Both approaches have the same O(log n) time complexity. However, the iterative approach (using a while loop) is generally more memory-efficient. Recursive versions can consume more memory because each function call adds a new layer to the system call stack, which could lead to a stack overflow error on extremely large datasets.

How does Binary Search handle duplicate values?

Standard Binary Search will return the index of any one of the matching values. If you need the first or last occurrence of a duplicate number, you must slightly modify the algorithm. Instead of stopping when you find the target, you record the current index and continue searching in the left half (for the first occurrence) or the right half (for the last occurrence).

Can Binary Search be used for strings or text?

Yes. Binary Search works on any data type that has a defined “Total Order,” meaning you can clearly say one item comes “before” another. As strings are sorted alphabetically (lexicographical order), you can use Binary Search to find words in a list exactly like you would find numbers in a sequence.

Why is the loop condition low <= high instead of low < high?

Using low <= high ensures that the algorithm checks the very last remaining element when the search space has narrowed down to a single item. If you used low < high, the loop would terminate prematurely, and you might miss the target if it happened to be that final element.

Share with others:

Unlock up to 68% off lifetime access to Coding Interview prep with Educative

Getting ready for coding interviews or sharpening your problem-solving skills? Unlock a lifetime discount with comprehensive resources designed to help you master technical interviews.

Data structures and algorithms

Pattern-based problem solving

Mock interview practice

Real-world coding challenges

Coding Interview Logo