Table of Contents
ResourcesBinary Search on Monotonic FunctionsFinding The Maximum x Such That f(x) = trueImplementation 1Implementation 2Finding The Minimum x Such That f(x) = trueExample - Maximum MedianCommon MistakesMistake 1 - Off By OneMistake 2 - Not Accounting for Negative BoundsMistake 3 - Integer OverflowProblemsUSACOGeneralQuizResources
| Resources | |||||
|---|---|---|---|---|---|
| CSA | animation, code, lower_bound + upper_bound | ||||
| CPH | code, lower_bound + upper_bound, some applications | ||||
| CF EDU | videos, problems similar to those covered in this module | ||||
| YouTube | video, good explanation | ||||
| KA | plenty of diagrams, javascript implementation | ||||
| IUSACO | module is based on this | ||||
| TC | similar material | ||||
| LC | many problems & applications | ||||
Note that the video above covers both binary search modules.
When we binary search, we start with a search space of size which we know the answer lies in. Then each iteration of the binary search cuts the search space in half, so the algorithm tests values. This is efficient and much better than testing each possible value in the search space.
Binary Search on Monotonic Functions
Let's say we have a boolean function f(x). Usually, in such problems, we want
to find the maximum or minimum value of such that f(x) is true. Similarly
to how binary search on an array only works on a sorted array, binary search on
the answer only works if the answer function is
monotonic, meaning that it
is always non-decreasing or always non-increasing.
Finding The Maximum x Such That f(x) = true
We want to construct a function lastTrue such that lastTrue(lo, hi, f)
returns the last x in the range [lo,hi] such that f(x) = true. If no such
x exists, then lastTrue should return lo-1.
This can be done with binary search if f(x) satisfies both of the following
conditions:
- If
f(x) = true, thenf(y) = truefor all . - If
f(x) = false, thenf(y) = falsefor all .
In other words, f must be true up to some point and false after it.
For example, if f(x) is given by the following function:
f(1) = true f(2) = true f(3) = true f(4) = true f(5) = true f(6) = false f(7) = false f(8) = false
then lastTrue(1, 8, f) = 5 and lastTrue(7, 8, f) = 6.
Implementation 1
As an exercise for the reader, verify that this implementation only calls f on values in the range [lo, hi].
from typing import Callabledef last_true(lo: int, hi: int, f: Callable[[int], bool]) -> int:"""Binary Search:param lo: lower bound:param hi: upper bound:param f: a function that returns whether a number is valid or not:return: the maximum x such that f(x) is true
See Lambda Expressions if you're not familiar with the syntax used in the program.
Implementation 2
This approach is based on interval jumping. We start at lo-1 and try jumps of
decreasing size, starting from hi - lo + 1 and halving the jump length each
time. For each jump length, we keep jumping forward as long as f stays true
at the landing point. As we get closer to the answer, the jumps get shorter.
This is conceptually similar to Binary Jumping.
from typing import Callabledef last_true(lo: int, hi: int, f: Callable[[int], bool]) -> int:"""Binary Search:param lo: lower bound:param hi: upper bound:param f: a function that returns whether a number is valid or not:return: the maximum x such that f(x) is true
Finding The Minimum x Such That f(x) = true
We want to construct a function firstTrue such that firstTrue(lo, hi, f)
returns the first x in the range [lo,hi] such that f(x) = true. If no such
x exists, then firstTrue should return hi+1.
Similarly to the previous part, this can be done with binary search if f(x)
satisfies both of the following conditions:
- If
f(x)is true, thenf(y)is true for all . - If
f(x)is false, thenf(y)is false for all .
We will need to do the same thing, but when the condition is satisfied, we will cut the right part, and when it's not, the left part will be cut.
from typing import Callabledef first_true(lo: int, hi: int, f: Callable[[int], bool]) -> int:hi += 1while lo < hi:mid = (lo + hi) // 2if f(mid):hi = midelse:
Example - Maximum Median
Focus Problem – try your best to solve this problem before continuing!
Statement: Given an array of integers, where is odd, we can perform the following operation on it times: take any element of the array and increase it by . We want to make the median of the array as large as possible after operations.
Constraints: , , , and is odd.
To get the current median, we first sort the array in ascending order.
Now, notice that to increase the current value to a value, say . All values currently greater than or equal to the median, must remain greater than or equal to the median.
For example, say we have the sorted array . The current median is , so to increase the median to , we have to increase the current median by and we also have to increase the 's to .
Following this idea, to increase the median to , we need to increase all values in the second half of the array to some value greater than or equal to .
Then, we binary search for the maximum possible median. We know that the number of operations required to raise the median to increases monotonically as increases, so we can use binary search. For a given median value , the number of operations required to raise the median to is
If this value is less than or equal to , then can be the median, so our
check function returns true. Otherwise, cannot be the median, so our check
function returns false.
Time Complexity: , where is the largest possible answer.
from typing import Callabledef med_reachable(x: int) -> bool:"""Checks whether the number of given operations is sufficientto raise the median of the array to x."""ops_needed = 0for i in range((size - 1) // 2, size):
Common Mistakes
Mistake 1 - Off By One
Consider the code from CSAcademy's Binary Search on Functions.
def f(x: int) -> int:return x * xdef sqrt(x: int) -> int:lo = 0hi = xwhile lo < hi:mid = (lo + hi) // 2if f(mid) <= x:lo = midelse:hi = mid - 1return lo
This results in an infinite loop if lo=0 and hi=1! In that case
mid = (0 + 1) / 2 = 0, and since f(0) <= x, we set lo = mid = 0, which
changes nothing. To fix this, round the midpoint up by setting
mid = (lo + hi + 1) / 2 instead:
def sqrt(x: int) -> int:lo = 0hi = xwhile lo < hi:mid = (lo + hi + 1) // 2 # round upif f(mid) <= x:lo = midelse:hi = mid - 1return lo
Mistake 2 - Not Accounting for Negative Bounds
Consider a slightly modified version of firstTrue:
from typing import Callabledef first_true(lo: int, hi: int, f: Callable[[int], bool]) -> int:hi += 1while lo < hi:mid = (lo + hi) // 2if f(mid):hi = midelse:lo = mid + 1return lo
In C++ and Java, this code does not necessarily work if lo + hi is negative
and odd. Consider the following example:
# Python's // floors, so this particular bug does NOT happen in Python:print(first_true(-10, -10, lambda x: False)) # outputs -9 (correct)print(first_true(-10, -10, lambda x: True)) # outputs -10 (correct)
This is because in C++ and Java, dividing an odd negative integer by two
truncates toward zero, which rounds it up instead of down (for example,
-19 / 2 = -9). Python's // operator rounds toward negative infinity, so
-19 // 2 = -10 and the bug does not occur there. Even so, writing
lo + (hi - lo) // 2 is still a good habit in every language.
from typing import Callabledef first_true(lo: int, hi: int, f: Callable[[int], bool]) -> int:hi += 1while lo < hi:mid = lo + (hi - lo) // 2if f(mid):hi = midelse:lo = mid + 1return lo
Mistake 3 - Integer Overflow
There are two ways to compute the midpoint, and each has its own overflow risk:
mid = lo + (hi - lo) / 2(used in ourfirstTrueabove) fails ifhi - loexceedsINT_MAX.mid = (lo + hi) / 2fails iflo + hiexceedsINT_MAXat any point during execution.
Also note that in our first_true and last_true code, we increment or decrement
the bounds, which if using INT_MAX or INT_MIN, may overflow. In general,
if concerned about overflow, consider using long long instead of int for the
bounds.
Problems
USACO
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| Silver | Easy | Show TagsBinary Search, Sorted Set | ||||
| Silver | Easy | Show TagsBinary Search, Sorting | ||||
| Silver | Easy | Show TagsBinary Search, Sorting | ||||
| Silver | Medium | Show TagsBinary Search, Sorting | ||||
| Gold | Hard | Show TagsBinary Search, Greedy, Sorting, Two Pointers | ||||
| Silver | Hard | Show TagsBinary Search, Sqrt | ||||
| Silver | Very Hard | Show TagsBinary Search | ||||
General
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CSES | Easy | Show TagsBinary Search | ||||
| CSES | Easy | Show TagsBinary Search | ||||
| CF | Easy | Show TagsBinary Search | ||||
| CC | Medium | Show Tags2D Prefix Sums, Binary Search | ||||
| CSES | Medium | Show TagsBinary Search | ||||
| CF | Medium | Show TagsBinary Search, Prefix Sums | ||||
| CF | Medium | Show TagsBinary Search | ||||
| CF | Medium | Show TagsBinary Search | ||||
| AC | Hard | Show TagsBinary Search, Prefix Sums, Sorting | ||||
| CF | Hard | Show TagsBinary Search, Prefix Sums | ||||
| CF | Hard | Show TagsBinary Search, Priority Queue | ||||
| CF | Hard | Show TagsBinary Search | ||||
| Baltic OI | Very Hard | Show TagsBinary Search, Stack | ||||
Quiz
What are the worst and best case time complexities for searching for a number in a sorted array of size with the following code?
def binary_search(x: int, a: list) -> bool:l = 0r = len(a) - 1while l <= r:m = (l + r) // 2if a[m] == x:return Trueelif x > a[m]:l = m + 1else:r = m - 1return False
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!