Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Binary Search

Binary Search

O(log n)

Halve the search space each step; the trick in variants is deciding which half is sorted / which side to keep.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksBinary Search on the AnswerBST LogicLongest Increasing SubsequenceMeet in the Middle+2
0%
mastery
0/39 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Sorted or rotated-sorted array, or a monotone yes/no predicate over indices: target, first/last position, insertion point, peak, O(log n).

  1. 1Brute force

    Linear scan O(n).

  2. 2The observation

    Examining every index: monotonicity of the predicate means one probe discards half the range.

  3. 3Why it works

    The answer always stays inside [lo, hi]: predicate false left of lo, true from the answer onward; each step drops a half that can't hold it.

Reach for it when

  • +Data is sorted (or rotated-sorted) and you want a value, an insertion point, or a first/last boundary.
  • +There's a monotonic predicate: as x increases, feasible goes false→true (or true→false) exactly once.
  • +Constraints scream log: n up to 1e9, or 'answer is a number in a huge range you can feasibility-test'.

Not when

  • ×Unsorted and no monotone test existsuse Sort first (O(n log n)), or a hash map / heap
  • ×k-th smallest over a streamuse Heap
  • ×Predicate isn't monotone; feasibility flips back and forthuse Ternary search if unimodal, else no binary search
  • ×Rotated array with duplicatesuse Expect O(n) worst case; shrink ends when lo, mid, hi are equal
  • ×Only membership matters, no order neededuse Hash set, O(1)

Intuition

Binary search is the "higher / lower" game. I'm thinking of a number 1–100; every guess I tell you higher or lower. You'd never go 1, 2, 3… you'd guess 50, halve the range, guess 25 or 75, and corner the number in ~7 guesses. Cutting the search space in half each step is what O(log n) means.

Read the full intuition

It only works on something monotonic — sorted data, or any yes/no test that flips from no→yes exactly once as the candidate grows. You keep a window [lo, hi], look at the middle, and throw away the half that cannot contain the answer.

Walk [1, 3, 5, 7, 9, 11, 13], find 7:

  • lo=0, hi=6, mid=3 → a[3]=7. Found. (Lucky middle!)

Find 9: mid=3→7, too small, so 9 is in the right half → lo=4. mid=5→11, too big → hi=4. mid=4→9. ✓

Key idea

The part everyone gets wrong is the boundary version: "find the first index that satisfies P." There you don't stop at a match — you record it and keep searching left, because an even-earlier one might exist. Master that and rotated-array / peak / first-last all fall out.

mid = lo + (hi - lo) // 2 (not (lo+hi)//2) avoids integer overflow in C++/Java — a habit worth keeping.

Why it costs what it costs

Time O(log n). the search interval halves every iteration, so it takes ⌈log₂ n⌉ steps to reach size 1.

Space O(1). iterative version keeps only lo/hi/mid; recursive version costs O(log n) stack.

Practice

Next · Foundation

Binary Search

Pick one loop template (half-open [lo, hi)) and keep it.

0/39 solved
  • Binary SearchFoundationFoundationAmazon, AdobeEasy
  • Search Insert PositionApply it · Return the insertion point.Apply itAmazon, AdobeEasy
  • First Bad VersionOne change · Search over a predicate, not values.One changeMeta, GoogleEasy
  • Find First and Last Position of Element in Sorted ArrayOne change · Two boundaries.One changeAmazon, MicrosoftMedium
  • Search in Rotated Sorted ArrayTwists · Array is only piecewise sorted.TwistsAmazon, MetaMedium
  • Find Peak ElementBranches · No sortedness at all.BranchesMeta, GoogleMedium
  • Single Element in a Sorted ArrayBranches · Predicate on index parity.BranchesAmazon, CitadelMedium
  • Random Pick with WeightCombine · Search a prefix-sum array.CombineMeta, GoogleMedium
  • Time Based Key-Value StoreAdvanced · Binary search inside a design problem.AdvancedStripe, GoogleMedium
  • Median of Two Sorted ArraysMastery checkMastery checkAmazon, AdobeHard
  • Search a 2D MatrixAmazon, MicrosoftMedium
  • Guess Number Higher or LowerGoogle, Morgan StanleyEasy

Pitfalls

Classic bugs

  • !while lo < hi with lo = mid (no +1) loops forever on two elements. Use <= with mid±1, or < with hi = mid / lo = mid+1.
  • !Inclusive vs exclusive hi: hi = len-1 pairs with lo <= hi; hi = len pairs with lo < hi. Never mix.
  • !(lo + hi) / 2 overflows in C++/Java; use lo + (hi - lo) / 2.
  • !First/last position: don't return on match; record it and keep narrowing toward the side you want.
  • !Rotated array: first decide which half is sorted, then check if the target lies inside it.
  • !Thinking it needs a sorted array: it needs a monotone predicate.
Go deepervariants and techniques · 4 combinations · interviewer follow-ups · resources

Variants and techniques

  • Ternary Search (unimodal optimisation)Minimise or maximise a unimodal function by discarding a third of the range per step (or binary search on f(m+1) - f(m) for integers).
  • Interactive Problems (query-limited search)CP 1600The input is hidden behind a query API with a budget. Design the queries (usually binary or ternary splits, sometimes comparison sorting) so the worst case fits the budget, and flush after each query.
  • Exact matchlo<=hi, return on equality, else move past mid. Plain Binary Search.
  • Lower / upper boundlo<hi, hi=mid on success — finds first index satisfying a predicate. First/Last Position, Search Insert Position.
  • Rotated sortedFind which half is sorted by comparing a[lo]/a[mid]; recurse into the half that could hold the target. Search in Rotated Sorted Array.
  • Peak / unsorted-but-monotone-locallyCompare a[mid] to a[mid+1] and walk uphill. Find Peak Element.
  • 2D matrix as 1DTreat an m×n row-sorted matrix as a length m·n array; map index → (row,col). Search a 2D Matrix.

Combinations

  • Longest Increasing Subsequence+Binary Search

    longest chain with n large

    Longest Increasing Subsequence:
    chain formulation
    Binary Search:
    finds the tail to replace

    Longest Increasing SubsequenceRussian Doll EnvelopesIncreasing Subsequence

  • Meet in the Middle+Binary Search

    n ~ 40 subset sum (exact, closest, count)

    Meet in the Middle:
    enumerates half-subsets
    Binary Search:
    matches each left sum to the best right sum

    Closest Subsequence SumPartition Array Into Two Arrays to Minimize Sum DifferenceMeet in the Middle

  • Interval Scheduling (sort by end)+1D / Fibonacci-style+Binary Search

    choose non-overlapping intervals maximising total weight (or at most k of them)

    Interval Scheduling (sort by end):
    sort by end so that compatible predecessors form a prefix
    1D / Fibonacci-style:
    dp[i] = max(dp[i-1], w_i + dp[p(i)])
    Binary Search:
    find the last job ending at or before the current start

    Maximum Profit in Job SchedulingMaximum Number of Events That Can Be Attended IIProjects

  • Interactive Problems (query-limited search)+Prefix Sum

    find the single altered element using range-sum queries within log n queries

    Interactive Problems (query-limited search):
    query a range sum and compare to binary search for the heavier element
    Prefix Sum:
    know the expected sum of any range

    Interview

Follow-ups interviewers ask

  1. 01What if the array is rotated? → decide which half is sorted each step, then test if the target lies in it.
  2. 02What if you can only probe values (no array), e.g. an API or a monotonic predicate? → that's binary search on the answer.
  3. 03Duplicates present and you need first/last? → don't stop on a match; record and keep narrowing toward the boundary.
  4. 04Search space is 2-D or a huge numeric range? → map to a 1-D index, or binary-search the value with a feasibility count.

State table

lo hi mid a[mid] vs 7 next
0 6 3 7 match? (find 9) a[3]=7<9 → lo=4
4 6 5 11 >9 hi=4
4 4 4 9 =9 found ✓

Resources

  • Binary searchcp-algorithms · article
  • Binary SearchUSACO Guide · course
  • ITMO Binary Search courseCodeforces EDU · course
  • Binary Search explore cardLeetCode · course
  • Sorting and searching cheatsheetTech Interview Handbook · article
Merge IntervalsBinary Search on the Answer
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial