Binary Search Pattern Hub
7 problemsBinary Search
easyClosed interval `[l, r]` invariant: `while l <= r`, compute `mid = l + ((r - l) >> 1)` preventing 32-bit overflow, adjust `l = mid + 1` or `r = mid - 1`.
Find Minimum in Rotated Sorted Array
mediumCompare `nums[mid]` strictly against `nums[r]` (the right boundary): if `nums[mid] > nums[r]`, the inflection point is strictly to the right (`l = mid + 1`); otherwise `mid` could be the minimum (`r = mid`).
Koko Eating Bananas
mediumMonotonic predicate on speed `k` over `[1 .. max(piles)]`: calculate `sum(ceil(p / k))` (`(p + k - 1) // k` integer ceiling). Find the smallest `k` where total hours <= `h`.
Longest Increasing Subsequence
mediumPatience sorting (`tails` invariant): maintain `tails[k]` = smallest possible tail value of any strictly increasing subsequence of length `k + 1`. Because `tails` stays strictly sorted, replace the first element `>= x` via `bisect_left` (or append when `x` exceeds all tails).
Search a 2D Matrix
mediumTreat the strictly row-major sorted `M x N` matrix as a flattened sorted 1D array `[0 .. M*N - 1]`, mapping index `mid` back to `(mid // N, mid % N)`.
Search in Rotated Sorted Array
mediumAt least one half (`[l..mid]` or `[mid..r]`) is guaranteed strictly sorted. Identify the sorted half via `nums[l] <= nums[mid]`, check whether `target` falls within its numeric bounds, and discard the other half.
Time Based Key-Value Store
mediumSince `set()` timestamps are strictly increasing per key, appending `(timestamp, value)` keeps the per-key list sorted automatically in O(1). `get()` binary searches the rightmost `t <= timestamp`.