Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 1 — Binary Search

Source: src/main/kotlin/binarysearch/ (22 problems)

Master idea: every problem in this chapter is a different face of the same theorem — if a predicate on a range is monotone, the boundary where it flips can be found in $O(\log n)$.

Prerequisites: the halving math in Reference: Big-O & Complexity Math.

Problems at a glance

#ProblemCore patternComplexityPage
1.1Koko Eating Bananasbinary search on the answer$O(n \log R)$
1.2Capacity To Ship Packages Within D Daysbinary search on the answer$O(n \log S)$
1.3Find First And Last Position Of Targetlower/upper bound$O(\log n)$
1.4Find K Closest Elementsbinary search on the start index$O(\log(n-k))$
1.5Find Minimum In Rotated Sorted Arrayrotated-array pivot$O(\log n)$
1.6Find Peak Elementmonotone slope descent$O(\log n)$
1.7Find Peak Element (Safe Boundaries)same, boundary-safe$O(\log n)$
1.8First Bad Versionlower bound (API predicate)$O(\log n)$
1.9Guess Number Higher Or Lowerexact-match ternary response$O(\log n)$
1.10House Robber IVbinary search on the answer$O(n \log V)$
1.11Kth Missing Positive Numberindex-space counting$O(\log n)$
1.12Median Of Two Sorted Arrayspartition-based search$O(\log \min(m,n))$
1.13Peak Index In A Mountain Arraymonotone slope descent$O(\log n)$
1.14Random Pick With Weightprefix sums + binary search$O(\log n)$ pick
1.15Search A 2D Matrixindex unrolling$O(\log(mn))$
1.16Search In Rotated Sorted Array IIrotated search + duplicate dedup$O(\log n)$ avg
1.17Search In Rotated Sorted Arrayrotated search$O(\log n)$
1.18Search Insert Positionlower bound$O(\log n)$
1.19Single Element In A Sorted Arrayparity-based search$O(\log n)$
1.20Valley Elementmonotone slope descent (mirror)$O(\log n)$
1.21Apartment Huntingbinary search + nearest neighbor$O(BR \log K)$
1.22Closest Subsequence Summeet-in-the-middle + binary search$O(2^{n/2} \log 2^{n/2})$

Reading order

Work through the sections in order the first time: 1.0 → 1.1 → 1.2 → 1.8 → 1.5 → 1.17 → 1.6 → 1.12. That path covers every sub-pattern (answer-space search, lower bound, rotated arrays, slope descent, partition search) with the minimum number of pages. The rest are variants and gyms that cement the same five moves.

Afterwards, close the book and try to derive 1.12’s partition condition from scratch — if you can, you own this chapter.