Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Binary Search High frequency Solution Available Practice Mode

Search a 2D Matrix LeetCode Solution

Tags: #Array #Binary Search #Matrix

Approach Summary

Treat the matrix as a flattened sorted array. Binary search on index 0..m*n-1, converting mid to (row, col) via division and modulo.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Binary Search Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Binary Search pattern.

Framework: Binary Search • Interview Prep: Tested at FAANG • Explore all Binary Search problems & invariants →

How to Recognize This Pattern

  • Rows sorted, first element of each row > last of previous
  • Binary search on virtual 1D array

Complexity Analysis

Time Complexity

O(log(m × n))

Space Complexity

O(1)

Tags

Array Binary Search Matrix

Frequently Asked Questions

What is the optimal time and space complexity for Search a 2D Matrix?
The optimal solution for Search a 2D Matrix achieves O(log(m × n)) runtime complexity and requires O(1) auxiliary space. Time Complexity is O(log(m*n)) because the algorithm processes elements efficiently in linear or logarithmic scans without unnecessary nested operations. Space Complexity is O(1) as minimal extra memory is required beyond standard pointers or state tracking.
How do I identify that Search a 2D Matrix requires the Binary Search pattern?
In technical interviews, look for key problem signals: Rows sorted, first element of each row > last of previous; Binary search on virtual 1D array. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Binary Search strategy.
What critical edge cases must be handled in Search a 2D Matrix?
Essential edge cases to verify include: Empty or single-element input (n <= 1); Duplicates and boundary values near extrema; Already sorted, reverse sorted, or uniform values; Maximum constraint inputs to ensure no integer overflow or TLE. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Search a 2D Matrix?
Search a 2D Matrix is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Microsoft, Google.
Buy me a coffee
Daily Practice
0/0