cswork / templatesOpen the Line 500 list

STOP 06 · LINEAR STRUCTURES

Binary Search and Answer Search

First true on a half-open range O(log n) checks

Contest ratings Rating 1182–Rating 1946· median Rating 1746(14 of 29 problems rated by zerotrac)

Open the Line 500 list · stop 06 · 29 problems
Learn first
Leads to
How often asked
asked by 7 companies · in 10 reportsTikTok / ByteDance 3, Rippling 2, Amazon 1, DoorDash 1, Goldman Sachs 1

Warm up with this one

LC 35Search Insert PositionEasy
Stuck? Peek at the approach

Find the first position not less than the target, unifying exact matches and insertion positions.

Key points

  1. Rewrite the problem as a monotonic check ok(x), false then true, and search for the first true.
  2. On the half-open range [lo, hi): set hi = mid when ok(mid), else lo = mid + 1; loop while lo < hi, and lo is the answer at the end.
  3. When the answer's range is known and a candidate can be checked in O(n), binary search the answer itself: minimum speed, maximise the minimum and so on.

Common pitfalls

  • lo = mid with a rounded-down mid loops forever; with this template only ever write lo = mid + 1.
  • (lo + hi) / 2 can overflow in C++, Java and Go; write lo + (hi - lo) / 2.
  • hi itself is never checked: pick an upper bound that is surely feasible, or a returned hi gets mistaken for an answer.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Binary search · drop half each step

Find 23 in a sorted array

Try your own input
20
51
82
123
164
235
386
567
CurrentDiscovered / computedAnswer
Target
23
left
0
right
7
mid
—

The search range starts as the whole sorted array. The small numbers are indexes.

InvariantIf the target exists, it is always inside the closed range [left, right].

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 35, with it.

Python
from typing import Callable


def first_true(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
    """Smallest x in [lo, hi) with ok(x), where ok goes False..False True..True; hi if none."""
    while lo < hi:
        mid = (lo + hi) // 2
        if ok(mid):
            hi = mid  # mid may be the answer: keep it in range
        else:
            lo = mid + 1
    return lo


def lower_bound(nums: list[int], target: int) -> int:
    """First index whose value is >= target (len(nums) if none)."""
    return first_true(0, len(nums), lambda i: nums[i] >= target)
C++
// Smallest x in [lo, hi) with ok(x), where ok goes false..false true..true; hi if none.
long long firstTrue(long long lo, long long hi, const function<bool(long long)>& ok) {
    while (lo < hi) {
        long long mid = lo + (hi - lo) / 2;
        if (ok(mid)) hi = mid;  // mid may be the answer: keep it in range
        else lo = mid + 1;
    }
    return lo;
}

// First index whose value is >= target (nums.size() if none).
int lowerBound(const vector<int>& nums, int target) {
    return firstTrue(0, nums.size(), [&](long long i) { return nums[i] >= target; });
}
Java
import java.util.function.LongPredicate;

class Solution {
    // Smallest x in [lo, hi) with ok(x), where ok goes false..false true..true; hi if none.
    long firstTrue(long lo, long hi, LongPredicate ok) {
        while (lo < hi) {
            long mid = lo + (hi - lo) / 2;
            if (ok.test(mid)) hi = mid; // mid may be the answer: keep it in range
            else lo = mid + 1;
        }
        return lo;
    }

    // First index whose value is >= target (nums.length if none).
    int lowerBound(int[] nums, int target) {
        return (int) firstTrue(0, nums.length, i -> nums[(int) i] >= target);
    }
}
Go
// firstTrue returns the smallest x in [lo, hi) with ok(x), where ok goes
// false..false true..true; hi if none. sort.Search is the same idea.
func firstTrue(lo, hi int, ok func(int) bool) int {
	for lo < hi {
		mid := lo + (hi-lo)/2
		if ok(mid) {
			hi = mid // mid may be the answer: keep it in range
		} else {
			lo = mid + 1
		}
	}
	return lo
}

// lowerBound returns the first index whose value is >= target (len(nums) if none).
func lowerBound(nums []int, target int) int {
	return firstTrue(0, len(nums), func(i int) bool { return nums[i] >= target })
}

Common variants

Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Peak finding: compare with the right neighbourO(log n) time · O(1) space

Without global order but with adjacent elements distinct, walking uphill always reaches a peak: nums[mid] < nums[mid + 1] puts a peak on the right, otherwise mid or something left of it is one. LC 162 (Find Peak Element) and LC 852 (Peak Index in a Mountain Array) use this comparison.

Python
def find_peak(nums: list[int]) -> int:
    """Index of an element larger than its neighbours (LC 162); adjacent values differ."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < nums[mid + 1]:  # uphill to the right: a peak lies in (mid, hi]
            lo = mid + 1
        else:  # downhill: mid or something left of it is a peak
            hi = mid
    return lo
C++
// Index of an element larger than its neighbours (LC 162); adjacent values differ.
int findPeak(const vector<int>& nums) {
    int lo = 0, hi = (int)nums.size() - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] < nums[mid + 1]) lo = mid + 1;  // uphill to the right: a peak lies in (mid, hi]
        else hi = mid;  // downhill: mid or something left of it is a peak
    }
    return lo;
}
Java
class Solution {
    // Index of an element larger than its neighbours (LC 162); adjacent values differ.
    int findPeak(int[] nums) {
        int lo = 0, hi = nums.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < nums[mid + 1]) lo = mid + 1; // uphill to the right: a peak lies in (mid, hi]
            else hi = mid; // downhill: mid or something left of it is a peak
        }
        return lo;
    }
}
Go
// findPeak returns the index of an element larger than its neighbours; adjacent values differ.
func findPeak(nums []int) int {
	lo, hi := 0, len(nums)-1
	for lo < hi {
		mid := lo + (hi-lo)/2
		if nums[mid] < nums[mid+1] { // uphill to the right: a peak lies in (mid, hi]
			lo = mid + 1
		} else { // downhill: mid or something left of it is a peak
			hi = mid
		}
	}
	return lo
}

Why it works

  1. Invariant: everything left of lo is false, and everything from hi on is true (or out of range). Setting hi = mid when ok(mid) holds and lo = mid + 1 otherwise both keep it. This needs ok to be monotone: all false, then all true.
  2. Termination: while lo < hi, mid = lo + (hi − lo) / 2 satisfies lo ≤ mid < hi, so the range strictly shrinks each round; when lo == hi, the invariant says it is the first true.
  3. Binary searching the answer works for the same reason: a faster speed or a looser limit can only make the goal easier, so the feasibility check is monotone in the answer.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
我先把问题改写成一个单调的判定 ok(x):前面一段全是 false,后面全是 true,然后找第一个 true。在半开区间 [lo, hi) 上,ok(mid) 为真就 hi = mid,否则 lo = mid + 1,始终保持 lo 左边都是 false、hi 往右都是 true。每轮区间严格变小,结束时 lo 等于 hi,就是答案。判定是 O(n) 的话,总复杂度是 O(n log 范围)。
English
I first rewrite the problem as a monotone check ok(x) that is false and then true, and search for the first true. On the half-open range from lo to hi, I set hi to mid when ok(mid) holds and lo to mid plus one otherwise, which keeps everything left of lo false and everything from hi on true. The range shrinks every round, and when lo meets hi that index is the answer. With an O(n) check the total cost is O(n log of the range).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. lo, hi = 0, len(a); while lo < hi: mid = (lo + hi) // 2; if a[mid] < x then lo = mid + 1 else hi = mid. On a sorted array a, what is lo when the loop ends?
  2. Binary search on the answer (bisect a range of candidate answers, testing each with check(mid)) requires:
  3. In Java or C++, why write mid = lo + (hi - lo) / 2 instead of mid = (lo + hi) / 2?
  4. Initially hi - lo = n, and each call to ok costs O(m). What is the time complexity?
    def first_true(lo, hi, ok):
        while lo < hi:
            mid = (lo + hi) // 2
            if ok(mid):
                hi = mid
            else:
                lo = mid + 1
        return lo
  5. a is sorted. What is the worst-case time complexity (n = len(a))?
    def contains(a, x):
        if not a:
            return False
        mid = len(a) // 2
        if a[mid] == x:
            return True
        if a[mid] < x:
            return contains(a[mid + 1:], x)
        return contains(a[:mid], x)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

from typing import Callable

Practice by stage

This stop's 29 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 2

#ProblemApproachRating
35Search Insert PositionFind the first position not less than the target, unifying exact matches and insertion positions.
852Peak Index in a Mountain ArrayBinary-search the transition from ascent to descent in a mountain array, controlling access to midpoint neighbors.Rating 1182

Core 19

#ProblemApproachRating
34Find First and Last Position of Element in Sorted ArraySearch for the left and right boundaries separately rather than finding an arbitrary duplicate and extending linearly.
33Search in Rotated Sorted ArrayIdentify which half is sorted to locate the target while maintaining the rotated-array search invariant.
153Find Minimum in Rotated Sorted ArrayCompare the midpoint with the right endpoint to locate the rotated minimum without discarding a possible answer.
162Find Peak ElementUse the local slope to choose a side that is still guaranteed to contain a peak.
74Search a 2D MatrixTreat the matrix as an implicit sorted array and convert between linear and row-column indices.
240Search a 2D Matrix IIUse ordering in both dimensions for rowwise binary search and compare it with linear elimination from the top-right corner.
275H-Index IIRecognize the monotonic condition between citation counts and remaining papers to locate the h-index boundary.
540Single Element in a Sorted ArrayUse the change in paired-index parity on either side of the single element to locate it.
2300Successful Pairs of Spells and PotionsSort one array and find the qualifying suffix for each threshold, avoiding multiplication overflow.Rating 1477
875Koko Eating BananasConvert a speed into a sum of rounded-up processing times and find the minimum feasible speed.Rating 1766
1011Capacity To Ship Packages Within D DaysSimulate the days needed for a candidate load capacity and binary-search the minimum feasible capacity.Rating 1725
1482Minimum Number of Days to Make m BouquetsCount contiguous available flower segments for a candidate date and find the earliest feasible date.Rating 1946
1283Find the Smallest Divisor Given a ThresholdEstablish that increasing the divisor decreases the sum of rounded-up quotients.Rating 1542
1760Minimum Limit of Balls in a BagTranslate a maximum bag size into the required number of splits, accounting for exact divisibility.Rating 1940
2187Minimum Time to Complete TripsConvert a time bound into the total trips completed by all vehicles and avoid overflow during accumulation.Rating 1641
2226Maximum Candies Allocated to K ChildrenCount recipients for a candidate portion size and find the largest feasible integer portion.Rating 1646
1898Maximum Number of Removable CharactersBuild a monotonic feasibility check from removal-order markers and a subsequence test.Rating 1913
1552Magnetic Force Between Two BallsSort positions and place balls greedily to binary-search the largest minimum separation.Rating 1920
1870Minimum Speed to Arrive on TimeSeparate rounded-up travel times on earlier segments from the actual final-segment time, handling floating-point boundaries.Rating 1676

Advanced 8

#ProblemApproachRating
81Search in Rotated Sorted Array IIHandle ambiguity caused by duplicate values and explain the degradation in worst-case complexity.
154Find Minimum in Rotated Sorted Array IIShrink carefully when duplicate values are equal, distinguishing justified elimination from ambiguous ranges.
410Split Array Largest SumUse greedy group counting to test a maximum group-sum limit, then binary-search the smallest feasible answer.
1802Maximum Value at a Given Index in a Bounded ArrayCompute the minimum sums on both sides under adjacent-difference constraints to test a proposed peak.Rating 1929
378Kth Smallest Element in a Sorted MatrixBinary-search the value range and count matrix elements no greater than the midpoint.
719Find K-th Smallest Pair DistanceAfter sorting, count pairs within a distance threshold using two pointers, then binary-search the distance.
1095Find in Mountain ArrayFind the peak, binary-search both sides, and cache accesses to stay within the interface-call limit.Rating 1827
4Median of Two Sorted ArraysBinary-search a partition in the shorter array and use the boundary conditions on both sides to obtain the combined median.

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.