Skip to content

Binary Search

Welcome to the Binary Search section. This module covers everything from the core algorithm to advanced applications and interview-ready patterns.


Binary search is a divide-and-conquer search algorithm that finds a target in a sorted collection by repeatedly halving the search space.

Instead of checking every element one-by-one (O(n)), binary search eliminates half of the remaining candidates on every step — achieving O(log n) time.

Searching for 35 in a sorted array of 1,000,000 elements:
Linear Search: up to 1,000,000 comparisons
Binary Search: at most 20 comparisons (log₂ 1,000,000 ≈ 20)

That is the power of logarithmic time.


  • Problems Overview — 10 problems from easy to hard
    • Search Rotated Sorted Array, Find Min Rotated, 2D Matrix, Peak Element, Koko Bananas, Ship Packages, Split Array, Sqrt(x), First Bad Version, Time-Based KV

StepFocusTopic
1UnderstandIntroduction — algorithm walkthrough and complexity
2Learn Patterns5 Patterns — templates for 95% of problems
3Practice10 Problems — apply patterns to classic problems
4DeepenAdvanced — floating-point, median, exponential
5PrepareInterview Questions — nail the verbal explanations

ScenarioExample
Sorted arrayFind a value, find first/last occurrence
Rotated sorted arrayFind value after rotation
Monotonic functionFind where f(x) crosses a threshold
Answer space”Find minimum X such that condition(X) is true”
2D matrix with sorted rowsSearch in row-major sorted grid
Floating-point precisionFind square root, cube root

The golden rule: If you can say “I can eliminate half the candidates” after one comparison, binary search applies.


OperationTimeSpace
Classic binary searchO(log n)O(1) iterative / O(log n) recursive
Find first / last occurrenceO(log n)O(1)
Binary search on answerO(log(range) × cost of check)O(1)
Exponential searchO(log n)O(1)

  • Arrays — Binary search operates on arrays
  • Recursion — Recursive binary search and divide-and-conquer
  • Sorting — Many sorting algorithms complement binary search