Skip to content
We areTOP 1%
DSA · Beginner · Pattern 6 of 11

Binary Search

12 problems.
Your progress0%
1st Visit
0/12
2nd Visit
0/12
Revise
0/12

About this pattern

Binary search halves a sorted search space at every step, finding a target or a boundary in O(log n). The most useful form is boundary search: find the first index where a monotone condition becomes true, such as the first element not less than x. Thinking in terms of that predicate avoids most off-by-one errors and also handles rotated arrays, where one half is always sorted.

Signals include a sorted input, queries asking how many elements are at most some value, and constraints such as n up to 10^5 with many queries. In C++, lower_bound and upper_bound perform boundary search directly on sorted ranges.

// First index in [lo, hi) where ok(i) is true; hi if none.
// Requires ok to be monotone: false ... false true ... true.
int firstTrue(int lo, int hi, const function<bool(int)>& ok) {
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (ok(mid)) hi = mid;
        else lo = mid + 1;
    }
    return lo;
}
// Built-in: int i = lower_bound(a.begin(), a.end(), x) - a.begin();

Problems

Binary Search questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Binary SearchLeetCodeEasy Solve Binary Search on LeetCode (opens in a new tab)
2Search Insert PositionLeetCodeEasy Solve Search Insert Position on LeetCode (opens in a new tab)
3First Bad VersionLeetCodeEasy Solve First Bad Version on LeetCode (opens in a new tab)
4LettersCodeforcesEasy 1000Solve Letters on Codeforces (opens in a new tab)
5Interesting drinkCodeforcesEasy 1100Solve Interesting drink on Codeforces (opens in a new tab)
6Eating QueriesCodeforcesEasy 1100Solve Eating Queries on Codeforces (opens in a new tab)
7Sum of CubesCodeforcesEasy 1100Solve Sum of Cubes on Codeforces (opens in a new tab)
8WormsCodeforcesEasy 1200Solve Worms on Codeforces (opens in a new tab)
9Find First and Last Position of Element in Sorted ArrayLeetCodeMedium Solve Find First and Last Position of Element in Sorted Array on LeetCode (opens in a new tab)
10Find Minimum in Rotated Sorted ArrayLeetCodeMedium Solve Find Minimum in Rotated Sorted Array on LeetCode (opens in a new tab)
11Search in Rotated Sorted ArrayLeetCodeMedium Solve Search in Rotated Sorted Array on LeetCode (opens in a new tab)
12Find Peak ElementLeetCodeMedium Solve Find Peak Element on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account