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

Learn the pattern · ~16 min

Binary Search

also called lower_bound/upper_bound, bisect

In a sorted array, compare with the middle and throw away the half that can't hold the answer, until one element (or none) is left.

Signalssorted array or a monotone yes/no predicate over indicesfirst/last position, insertion pointrotated sorted array, peak finding
Cheat sheet and practice

Reach for it when you read

  • +A sorted array and you need a value, its first or last position, or where it would be inserted.
  • +n up to 10⁵ or more with many lookups: O(log n) per question instead of a scan.
  • +A yes/no question about an index that is no, no, …, yes, yes along the array (first bad version, the minimum of a rotated array), or one that says which half holds the answer (a peak).
  • +"Find it in O(log n)" written in the problem.

Not this one when

  • ×The answer is a number you guess and check (a speed, a capacity, a day), not a position: binary search on the answer.
  • ×The array isn't sorted and nothing flips once along it: sort first, or use a hash map for lookups.
  • ×A contiguous subarray with a sum condition on positive numbers: a sliding window is O(n).

Learn Binary Search

First, what does "binary" mean here?

Binary means two. Binary search checks the middle of what's left and keeps only the half that can still hold the answer. 8 items become 4, 2, 1, so at most 4 checks. 10⁵ items need at most 17, 10⁹ at most 30.

It needs the array sorted: that's what tells you which half to throw away.

How does halving find a number?

Find 19 in [3, 7, 11, 15, 19, 24, 30, 42]. lo and hi mark the part that can still hold it.

Look at the middle. If it's smaller than the target, the target can only be to its right. If it's bigger, only to its left.

lo hi mid a[mid] what happens
0 7 3 15 15 < 19: everything from 0 to 3 is too small, lo = 4
4 7 5 24 24 > 19: everything from 5 to 7 is too big, hi = 4
4 4 4 19 found at index 4

Search for 20 instead: at index 4, 19 < 20 gives lo = 5. Now lo > hi, nothing is left: the answer is -1.

The code for it

C++
int search(vector<int>& a, int target) {
    int lo = 0, hi = (int)a.size() - 1;      // both ends inclusive
    while (lo <= hi) {                        // something is left
        int mid = lo + (hi - lo) / 2;         // (lo + hi) / 2 can overflow
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

You don't need to memorise this. It's the table: check the middle, move past it, stop when nothing's left.

Why lo = mid + 1 and not lo = mid? mid is already checked. Keep it and you can get stuck: with lo = 4, hi = 5 and a bigger target, mid is 4 forever.

Fine, but how does this help us?

A classic: Find First and Last Position of Element in Sorted Array. In [2, 4, 4, 4, 7, 9], where does the block of 4s start and end? (Missing: [-1, -1].)

i a[i] is it 4?
0 2 no
1 4 yes: the first one
2 4 yes
3 4 yes: the last one
4 7 no
5 9 no

So the answer is [1, 3]. For 5 it's [-1, -1].

The brute force

Scan the array and remember the first and last match:

C++
vector<int> searchRangeScan(vector<int>& a, int x) {
    int first = -1, last = -1;
    for (int i = 0; i < (int)a.size(); i++)
        if (a[i] == x) { if (first == -1) first = i; last = i; }
    return {first, last};
}

That's O(n), and the problem says you must write O(log n). Honestly, the judge won't catch it: one scan of 10⁵ items is instant. It hurts when one array gets many questions: 10⁵ of them on 10⁵ items took 9.6 s. Finding one 4 with search and walking outwards is no better: if every value is 4, the walk is O(n).

The one thought that fixes it

Run search for 4. Its first check is index 2, and a[2] is 4. But is it the first 4? Index 1 holds one too, and from index 2 alone you can't tell.

So change the question. Not "is this a 4?" but is a[i] ≥ 4? Down the array: no, yes, yes, yes, yes, yes. Sorted order makes it flip once, and the first yes is where the 4s start:

  • Yes at mid (index 3): everything right of it is yes too, so the first yes is mid or left of it. Keep mid: hi = mid.
  • No at mid (index 0, 2 < 4): everything left of it is no too, so the first yes is to the right: lo = mid + 1.

That's the halving from before, with a yes/no question instead of "equal?". The end of the block is the same search: the first a[i] ≥ 5 is at 4, so the last 4 is at 3.

C++
int firstAtLeast(vector<int>& a, int x) {   // first i with a[i] >= x, or n
    int lo = 0, hi = a.size();              // hi = n: "none" is a valid answer
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] >= x) hi = mid;          // mid may be the first: keep it
        else lo = mid + 1;
    }
    return lo;
}
vector<int> searchRange(vector<int>& a, int x) {
    int first = firstAtLeast(a, x);
    if (first == (int)a.size() || a[first] != x) return {-1, -1};
    return {first, firstAtLeast(a, x + 1) - 1};
}

Dry run

Same array, [2, 4, 4, 4, 7, 9]. The range is [lo, hi): hi itself is never checked.

x lo hi mid what happens
4 0 6 3 4 ≥ 4, yes: the first is 3 or left, hi = 3
4 0 3 1 4 ≥ 4, yes: hi = 1
4 0 1 0 2 ≥ 4, no: lo = 1. Now lo = hi: first = 1
5 0 6 3 4 ≥ 5, no: lo = 4
5 4 6 5 9 ≥ 5, yes: hi = 5
5 4 5 4 7 ≥ 5, yes: hi = 4. last = 4 − 1 = 3

[1, 3], the same answer as the brute force.

Why it's O(log n)

Count the size of [lo, hi): here 6, 3, 1, 0. Every check keeps at most half, so 10⁵ items take at most 17 checks per search. That's O(log n) time and O(1) space.

From O(n) down to O(log n), by asking a question that flips once and halving towards the flip.

Search insert position, first bad version? The same function

Where would target go to keep the array sorted? At the first element at least as big: firstAtLeast(a, target). In [1, 3, 5, 6], 5 goes at 2, 2 at 1, 7 at 4.

In First Bad Version the row is handed to you: versions 1..n answer no, …, no, yes, …, yes. Use lo = 1, hi = n and ask isBadVersion(mid) instead of a[mid] >= x.

Peak element? A question that says which side

Find Peak Element: return any index that's bigger than both neighbours (outside the array counts as −∞, and neighbours are never equal). [1, 2, 1, 3, 5, 6, 4] isn't sorted, and no question flips once along it. But compare a[mid] with a[mid + 1]:

  • Going up: from mid + 1 the values either rise to the end (the last one is a peak) or fall somewhere (the top before the fall is a peak). A peak is to the right: lo = mid + 1.
  • Going down: by the same argument, mid or something left of it is a peak: hi = mid.
C++
int lo = 0, hi = (int)a.size() - 1;
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (a[mid] < a[mid + 1]) lo = mid + 1;   // uphill to the right
    else hi = mid;
}
// lo is a peak

The checks: mid 3 (3 < 5, up), mid 5 (6 > 4, down), mid 4 (5 < 6, up). It stops on index 5, the 6. Index 1 is a peak too; any one counts. So binary search doesn't need sorted order. It needs a check that says which half surely still holds an answer.

Rotated sorted array? Find the sorted half

Search in Rotated Sorted Array: find 0 in [4, 5, 6, 7, 0, 1, 2], a sorted array turned at some point. Check a[mid] first. If it's not the target, one side of it is sorted: the left (lo..mid) if a[lo] <= a[mid], else the right. Its two ends tell you whether the target is inside. If so, keep that side without mid; if not, the other.

lo hi mid a[mid] what happens
0 6 3 7 left half 4..7 is sorted, 0 isn't in it: lo = 4
4 6 5 1 left half 0..1 is sorted, 0 is in it: hi = 4
4 4 4 0 found at index 4

Remember this

  • You need a question that flips once (sorted order gives one), or one that says which half still holds an answer (the peak, the rotated array).
  • Pick one loop shape and keep it: lo <= hi with hi = mid − 1, or lo < hi with hi = mid. Mixing them loops forever or skips answers.
  • Rotated with duplicates: a[lo] == a[mid] == a[hi] hides the sorted half. Move both ends inwards; the worst case is O(n).
  • Whenever a problem says "sorted" and wants a position, a first or a last, or asks for O(log n), it's binary search.

Practise it on Binary Search, then Search Insert Position, First Bad Version, Find First and Last Position of Element in Sorted Array, Search in Rotated Sorted Array (the sorted half) and Find Peak Element (a slope).

Below, watch Binary Search run line by line.

Watch it work, line by line

Binary Search ↗, a = [1, 3, 7, 9, 11, 15, 20, 24, 30], target = 15 → 5. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is there an order (sorted values, or a yes/no question about each index that flips only once), so that one look at the middle tells me which half to throw away?

Reach for it when

  • +sorted array or a monotone yes/no predicate over indices
  • +first/last position, insertion point
  • +rotated sorted array, peak finding
  • +O(log n) required
  • +n up to 1e9 indices or values; log n steps

It fails 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)

Looks like it, isn't (and the other way round)

  • Median of Two Sorted Arrays looks like K-way Merge, needs this pattern

    Merging is O(m + n); binary searching the partition is O(log min(m, n)).

  • Random Pick with Weight looks like Reservoir Sampling, needs this pattern

    Weights known upfront: prefix sums + binary search, not reservoir sampling.

  • Find Peak Element looks like Two Pointers, needs this pattern

    No sortedness, but the local slope gives a monotone predicate for binary search.

Why this pattern and not another

There's a monotonic structure — sorted data or a predicate that flips false→true exactly once — so each comparison eliminates half the space in O(log n).

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1What does binary search really need: a sorted array, or something more general?Reveal

    A yes/no question about indices (or values) that flips only once. A sorted array is one way to get it.

  • 2Which update rules go with while (lo <= hi), and which with while (lo < hi)?Reveal

    lo <= hi with inclusive hi and lo = mid + 1 / hi = mid - 1. lo < hi with hi = mid / lo = mid + 1. Mixing them loops forever or skips the answer.

  • 3Why write lo + (hi - lo) / 2?Reveal

    lo + hi can overflow int when both are near 2³¹. This form never exceeds hi.

  • 4On [1, 3, 3, 7, 7, 7, 7, 9, 12], what do lower_bound(7) and upper_bound(7) return, and what's the count of 7s?Reveal

    lower_bound is the first index with a[i] >= 7: 3. upper_bound is the first with a[i] > 7: 7. The count is 7 − 3 = 4.

Practice ladder

every problem →
  1. 1Binary Searchthe hookEasy
  2. 2Search Insert Positionboundary formEasy
  3. 3First Bad Versionboundary formEasy
  4. 4Find First and Last Position of Element in Sorted Arrayfirst and lastMedium
  5. 5Find Minimum in Rotated Sorted ArrayrotatedMedium
  6. 6Search in Rotated Sorted ArrayrotatedMedium
  7. 7Find Peak ElementslopeMedium
  8. 8Single Element in a Sorted Arrayhidden yes/noMedium

Finished Binary Search? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Binary Search

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial