When to use
Binary search works on any monotonic predicate, not just sorted arrays. Pattern: "find minimum X such that condition(X) is true" — binary search on the answer space.
Rules
- Use bisect.bisect_left/bisect_right for sorted-array insertion points
- For "minimize the maximum" or "maximize the minimum" problems, binary search on the answer and check feasibility
- ALWAYS use lo + (hi - lo) // 2 to avoid overflow
- When searching rotated arrays, check which half is sorted first
- NEVER binary search on unsorted data without a monotonic predicate
Complexity
Time: O(log n) — whenever you see "sorted" or "monotonic" in a problem, consider binary search.
Example
"Minimize maximum load" → binary search on answer space. Check if feasible(mid) divides into k groups each ≤ mid. Use lo + (hi - lo) // 2 to avoid overflow.
1---
2name: binary-search
3description: "Search on monotonic predicates for sorted arrays, answer spaces, and rotated arrays. Use when finding minimum/maximum values, insertion points, or solving 'minimize the maximum' problems."
4topic: Binary Search
5token_cost: 90
6related: [sorting-choice, two-pointers, hash-vs-tree]
7keywords:
8 [
9 binary,
10 search,
11 sorted,
12 monotonic,
13 bisect,
14 minimum,
15 maximum,
16 feasible,
17 predicate,
18 lower,
19 upper,
20 bound,
21 log,
22 efficient,
23 mid,
24 pivot,
25 rotated,
26 ]
27metadata:
28 source: https://skillmd.com/skills/aibot88/binary-search
29---
30
31## When to use
32
33Binary search works on any monotonic predicate, not just sorted arrays. Pattern: "find minimum X such that condition(X) is true" — binary search on the answer space.
34
35## Rules
36
37- Use bisect.bisect_left/bisect_right for sorted-array insertion points
38- For "minimize the maximum" or "maximize the minimum" problems, binary search on the answer and check feasibility
39- ALWAYS use lo + (hi - lo) // 2 to avoid overflow
40- When searching rotated arrays, check which half is sorted first
41- NEVER binary search on unsorted data without a monotonic predicate
42
43## Complexity
44
45Time: O(log n) — whenever you see "sorted" or "monotonic" in a problem, consider binary search.
46
47## Example
48
49"Minimize maximum load" → binary search on answer space. Check if `feasible(mid)` divides into k groups each ≤ mid. Use `lo + (hi - lo) // 2` to avoid overflow.