Home / Patterns / Binary Search

Binary Search Pattern Hub

7 problems

Binary Search

easy
TC: O(log N) · SC: O(1)

Closed 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

medium
TC: O(log N) · SC: O(1)

Compare `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

medium
TC: O(N log M) · SC: O(1)

Monotonic 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

medium
TC: O(N log N) · SC: O(N)

Patience 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

medium
TC: O(log(M * N)) · SC: O(1)

Treat 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

medium
TC: O(log N) · SC: O(1)

At 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

medium
TC: O(log N) · SC: O(N)

Since `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`.