Skip to the solution
MediumDSA12 min read

How do you search a sorted 2D matrix?

693 views

The problem

Question presented to candidate: "You are given a matrix of integers that is sorted, and a target. Return whether the target is in the matrix. Please write it in Python, and tell me how your approach depends on how exactly the matrix is sorted."

What a strong answer should cover:

  • Asks which shape: rows chaining into one sorted sequence (LeetCode 74) or rows and columns sorted independently (LeetCode 240).
  • Shape 1: binary search over 0 .. m*n - 1 with index mapping divmod(mid, cols), O(log(m n)) time, O(1) space.
  • Shape 2: staircase walk from the top-right corner, dropping a row or column per step, O(m + n), with the reason the top-left corner does not work.
  • Brute force O(m n) and row-by-row bisect O(m log n) as baselines.
  • Python specifics: divmod, guarding matrix[0] on an empty list (IndexError), // not /, and the [[0] * n] * m aliasing trap when building test matrices.

Clarifying questions expected:

  • "Does each row start after the previous row ends, or are rows and columns sorted separately?"
  • "Return a boolean or the position?"
  • "Can the matrix or its rows be empty?"

Code / implementation expected: Yes โ€” search_matrix(matrix, target) for Shape 1 and a staircase function for Shape 2, in Python.

  • dsa
  • binary-search
  • matrix

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonShape 1: flattened binary search on nine inputs
PythonShape 2: staircase path, brute-force check, and why flattening fails
PythonProbe counts on a 1000 x 1000 matrix: flattened vs staircase

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 74 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

When would you use BFS over Dijkstra for shortest paths?

Continue