Search a 2D Matrix - Binary Search Pattern

Search a 2D Matrix in Java using the Binary Search pattern: problem statement, approach, template, complexity, and interview tips.

Search a 2D Matrix

Problem Statement

Search for a value in a matrix whose rows are sorted and where each row starts after the previous row ends.

Halve the search space each step, on a sorted array or on a monotonic answer range.

Use this pattern when the data is sorted or rotated, or the answer lies in a range where a yes/no check is monotonic.

Approach

  1. Define lo and hi and the invariant that the answer lies between them.
  2. Compute mid safely and discard the half that cannot contain the answer.
  3. Stop when the range is empty or the answer is found.

Pattern Template (Java)

int lo = 0, hi = n - 1;
while (lo <= hi) {
    int mid = lo + (hi - lo) / 2;
    if (nums[mid] == target) return mid;
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}
return -1;

Adapt this template to the exact rules of Search a 2D Matrix: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(log n) time and O(1) space.

Interview Tips

  • Use lo + (hi - lo) / 2 to avoid integer overflow.
  • For answer-range problems, binary search on the answer and write a separate feasibility check.
  • Start with a brute-force idea, state its complexity, then explain how the Binary Search pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Find Minimum in Rotated Sorted Array | Next: Koko Eating Bananas

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.