DSA: Binary Search & Matrix Search Variants
When to use
Use this skill when querying sorted or rotated collections, or when the problem statement asks for the 'minimum maximum' or 'maximum minimum' feasible value (binary search on answer).
Core principles
- Search Space Elimination: Binary search does not require a fully sorted array; it only requires a monotonic predicate where an evaluation at
middecisively eliminates half the search space. - Integer Overflow Prevention: Compute midpoint as
mid = low + (high - low) // 2rather than(low + high) // 2to prevent 32-bit integer overflow. - Loop Invariant & Boundary Selection: Standardize on
while low <= high: when target is not found,high = mid - 1andlow = mid + 1. - Virtual Matrix Flattening: For an
m x nrow-sorted matrix, map indexkto 2D coordinates viarow = k // nandcol = k % n.
Step-by-step workflow
- Define the search space boundaries
lowandhigh. - For rotated arrays: determine which half is normally sorted (
nums[low] <= nums[mid]). - Check if target lies within the cleanly sorted half; adjust
loworhighaccordingly. - For search on answer: write a helper
is_feasible(mid)returning boolean. - Iterate until
low > high. - Return target index or the optimal boundary.
Specifics & examples
# Search in Rotated Sorted Array: O(log N) Time, O(1) Space
def search_rotated(nums: list[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]: # Left half is sorted
if nums[low] <= target < nums[mid]: high = mid - 1
else: low = mid + 1
else: # Right half is sorted
if nums[mid] < target <= nums[high]: low = mid + 1
else: high = mid - 1
return -1
Common mistakes & pitfalls
- Infinite loops caused by
low = midwithout integer ceiling division. - Off-by-one errors in boundary adjustments (
high = midvshigh = mid - 1). - Failing to recognize that 'find the minimum capacity' is a binary search on the answer space.
Verification checklist
- Midpoint calculation prevents integer overflow.
- While loop condition (
low <= high) guarantees termination. - Validated against target not present and array length 1.
Related skills
- dsa-arrays-hashing-two-pointers-sliding-window
- dsa-time-space-complexity-big-o-analysis
- coding-interview-communication-thinking-out-loud
- dsa-greedy-algorithms-interval-scheduling