STOP 06 · LINEAR STRUCTURES
Binary Search and Answer Search
First true on a half-open range O(log n) checks
- 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 PositionStuck? Peek at the approach
Find the first position not less than the target, unifying exact matches and insertion positions.
Key points
- Rewrite the problem as a monotonic check ok(x), false then true, and search for the first true.
- 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.
- 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.
Binary search · drop half each step
Find 23 in a sorted array
Try your own input
- 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.
Binary search on the answerO(n log M) time, M the answer range · O(1) space
When the question asks for the smallest workable speed, capacity or day count, and workability is monotone in the answer (a faster speed always finishes), binary search the range of answers and test each mid with an O(n) check. LC 875 (Koko Eating Bananas), LC 1011 and LC 410 have this shape.
Python
def min_speed(piles: list[int], hours: int) -> int:
"""Smallest eating speed that finishes every pile within hours (LC 875)."""
def ok(speed: int) -> bool: # monotone: a faster speed never needs more hours
return sum((p - 1) // speed + 1 for p in piles) <= hours
lo, hi = 1, max(piles) # the answer is in [lo, hi]; hi always works
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid # mid works: the answer is mid or smaller
else:
lo = mid + 1
return loC++
// Smallest eating speed that finishes every pile within hours (LC 875).
int minSpeed(const vector<int>& piles, long long hours) {
auto ok = [&](int speed) { // monotone: a faster speed never needs more hours
long long need = 0;
for (int p : piles) need += (p - 1) / speed + 1;
return need <= hours;
};
int lo = 1, hi = *max_element(piles.begin(), piles.end()); // the answer is in [lo, hi]
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ok(mid)) hi = mid; // mid works: the answer is mid or smaller
else lo = mid + 1;
}
return lo;
}Java
class Solution {
// Smallest eating speed that finishes every pile within hours (LC 875).
int minSpeed(int[] piles, long hours) {
int lo = 1, hi = Arrays.stream(piles).max().getAsInt(); // the answer is in [lo, hi]
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ok(piles, hours, mid)) hi = mid; // mid works: the answer is mid or smaller
else lo = mid + 1;
}
return lo;
}
// Monotone: a faster speed never needs more hours.
private boolean ok(int[] piles, long hours, int speed) {
long need = 0;
for (int p : piles) need += (p - 1) / speed + 1;
return need <= hours;
}
}Go
import "slices"
// minSpeed returns the smallest eating speed that finishes every pile within hours (LC 875).
func minSpeed(piles []int, hours int) int {
ok := func(speed int) bool { // monotone: a faster speed never needs more hours
need := 0
for _, p := range piles {
need += (p-1)/speed + 1
}
return need <= hours
}
lo, hi := 1, slices.Max(piles) // the answer is in [lo, hi]
for lo < hi {
mid := lo + (hi-lo)/2
if ok(mid) {
hi = mid // mid works: the answer is mid or smaller
} else {
lo = mid + 1
}
}
return lo
}Rotated array: find the sorted half firstO(log n) time · O(1) space
A sorted array rotated once (LC 33, LC 153) is no longer monotone, but at least one half around mid is sorted: nums[lo] <= nums[mid] means the left half is, and then the target either falls inside that sorted half or it does not. Use the closed range [lo, hi] and return on a hit.
Python
def search_rotated(nums: list[int], target: int) -> int:
"""Index of target in a rotated sorted array of distinct values, or -1 (LC 33)."""
lo, hi = 0, len(nums) - 1 # closed range [lo, hi]
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # the left half [lo, mid] is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # the right half [mid, hi] is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1C++
// Index of target in a rotated sorted array of distinct values, or -1 (LC 33).
int searchRotated(const vector<int>& nums, int target) {
int lo = 0, hi = (int)nums.size() - 1; // closed range [lo, hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[lo] <= nums[mid]) { // the left half [lo, mid] is sorted
if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
} else { // the right half [mid, hi] is sorted
if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}Java
class Solution {
// Index of target in a rotated sorted array of distinct values, or -1 (LC 33).
int searchRotated(int[] nums, int target) {
int lo = 0, hi = nums.length - 1; // closed range [lo, hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[lo] <= nums[mid]) { // the left half [lo, mid] is sorted
if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
} else { // the right half [mid, hi] is sorted
if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}
}Go
// searchRotated returns the index of target in a rotated sorted array of distinct values, or -1.
func searchRotated(nums []int, target int) int {
lo, hi := 0, len(nums)-1 // closed range [lo, hi]
for lo <= hi {
mid := lo + (hi-lo)/2
if nums[mid] == target {
return mid
}
if nums[lo] <= nums[mid] { // the left half [lo, mid] is sorted
if nums[lo] <= target && target < nums[mid] {
hi = mid - 1
} else {
lo = mid + 1
}
} else { // the right half [mid, hi] is sorted
if nums[mid] < target && target <= nums[hi] {
lo = mid + 1
} else {
hi = mid - 1
}
}
}
return -1
}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 loC++
// 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
- 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.
- 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.
- 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 范围)。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.
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
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
| # | Problem | Approach | Rating |
|---|---|---|---|
| 35 | Search Insert Position | Find the first position not less than the target, unifying exact matches and insertion positions. | |
| 852 | Peak Index in a Mountain Array | Binary-search the transition from ascent to descent in a mountain array, controlling access to midpoint neighbors. |
Core 19
| # | Problem | Approach | Rating |
|---|---|---|---|
| 34 | Find First and Last Position of Element in Sorted Array | Search for the left and right boundaries separately rather than finding an arbitrary duplicate and extending linearly. | |
| 33 | Search in Rotated Sorted Array | Identify which half is sorted to locate the target while maintaining the rotated-array search invariant. | |
| 153 | Find Minimum in Rotated Sorted Array | Compare the midpoint with the right endpoint to locate the rotated minimum without discarding a possible answer. | |
| 162 | Find Peak Element | Use the local slope to choose a side that is still guaranteed to contain a peak. | |
| 74 | Search a 2D Matrix | Treat the matrix as an implicit sorted array and convert between linear and row-column indices. | |
| 240 | Search a 2D Matrix II | Use ordering in both dimensions for rowwise binary search and compare it with linear elimination from the top-right corner. | |
| 275 | H-Index II | Recognize the monotonic condition between citation counts and remaining papers to locate the h-index boundary. | |
| 540 | Single Element in a Sorted Array | Use the change in paired-index parity on either side of the single element to locate it. | |
| 2300 | Successful Pairs of Spells and Potions | Sort one array and find the qualifying suffix for each threshold, avoiding multiplication overflow. | |
| 875 | Koko Eating Bananas | Convert a speed into a sum of rounded-up processing times and find the minimum feasible speed. | |
| 1011 | Capacity To Ship Packages Within D Days | Simulate the days needed for a candidate load capacity and binary-search the minimum feasible capacity. | |
| 1482 | Minimum Number of Days to Make m Bouquets | Count contiguous available flower segments for a candidate date and find the earliest feasible date. | |
| 1283 | Find the Smallest Divisor Given a Threshold | Establish that increasing the divisor decreases the sum of rounded-up quotients. | |
| 1760 | Minimum Limit of Balls in a Bag | Translate a maximum bag size into the required number of splits, accounting for exact divisibility. | |
| 2187 | Minimum Time to Complete Trips | Convert a time bound into the total trips completed by all vehicles and avoid overflow during accumulation. | |
| 2226 | Maximum Candies Allocated to K Children | Count recipients for a candidate portion size and find the largest feasible integer portion. | |
| 1898 | Maximum Number of Removable Characters | Build a monotonic feasibility check from removal-order markers and a subsequence test. | |
| 1552 | Magnetic Force Between Two Balls | Sort positions and place balls greedily to binary-search the largest minimum separation. | |
| 1870 | Minimum Speed to Arrive on Time | Separate rounded-up travel times on earlier segments from the actual final-segment time, handling floating-point boundaries. |
Advanced 8
| # | Problem | Approach | Rating |
|---|---|---|---|
| 81 | Search in Rotated Sorted Array II | Handle ambiguity caused by duplicate values and explain the degradation in worst-case complexity. | |
| 154 | Find Minimum in Rotated Sorted Array II | Shrink carefully when duplicate values are equal, distinguishing justified elimination from ambiguous ranges. | |
| 410 | Split Array Largest Sum | Use greedy group counting to test a maximum group-sum limit, then binary-search the smallest feasible answer. | |
| 1802 | Maximum Value at a Given Index in a Bounded Array | Compute the minimum sums on both sides under adjacent-difference constraints to test a proposed peak. | |
| 378 | Kth Smallest Element in a Sorted Matrix | Binary-search the value range and count matrix elements no greater than the midpoint. | |
| 719 | Find K-th Smallest Pair Distance | After sorting, count pairs within a distance threshold using two pointers, then binary-search the distance. | |
| 1095 | Find in Mountain Array | Find the peak, binary-search both sides, and cache accesses to stay within the interface-call limit. | |
| 4 | Median of Two Sorted Arrays | Binary-search a partition in the shorter array and use the boundary conditions on both sides to obtain the combined median. |
OA questions on this topic 118
- Build Blocks and Obstacles on a Number LineMeta
- Find Peak ElementMeta
- Kth Missing Positive Number (for E4 :)Meta
- Get Smaller ItemsAmazon
- Get Computational EquivalentsAmazon
- Find Minimum MaximumAmazon
- Domino Removal ProblemAmazon
- Get Max Matching (Match the Column)Amazon
- Get Min Time (Earliest Time Usage ≥ Max)Amazon
- Count Bought Items (Recurring Shop Purchase)Amazon
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.