Binary Search on a Sorted Array
| Resources | |||||
|---|---|---|---|---|---|
| Python | |||||
| GFG | |||||
Please check the Binary Search module for additional resources (though they cover additional material not part of this module).
Example - Counting Haybales
Focus Problem – try your best to solve this problem before continuing!
View Internal SolutionAs each of the points are in the range , storing locations of haybales in a boolean array and then taking prefix sums of that would take too much time and memory.
Instead, let's place all of the locations of the haybales into a list and sort it. Now we can use binary search to count both the number of haybales with position at most and the number of haybales with position less than in time, and then subtract these two quantities to get the final answer.
Without Built-in Functions
def at_most(x: int) -> int:lo = 0hi = len(bales)while lo < hi:mid = (lo + hi) // 2if bales[mid] <= x:lo = mid + 1else:hi = midreturn lo
With Built-in Functions
We can use the builtin
bisect.bisect
function.
from bisect import bisectinp = open("haybales.in", "r")out = open("haybales.out", "w")bale_num, query_num = map(int, inp.readline().split())bales = sorted(list(map(int, inp.readline().split())))for _ in range(query_num):start, end = map(int, inp.readline().split())print(bisect(bales, end) - bisect(bales, start - 1), file=out)
Problems
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CF | Easy | Show Tags2P, Binary Search | ||||
| Silver | Easy | Show TagsBinary Search | ||||
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!