Tensorum
LeetCode 74 · 2D Matrix

Search a 2D Matrix

LeetCode 74 · Medium · solution, intuition & step-by-step walkthrough

Treat the matrix as a flat sorted array.

MediumArrayBinary SearchMatrix
0 msruntime · beats 100%
18.5 MBmemory · beats 100%
1approach
5accepted runs · last 17 Aug 2025

This is how I solved Search a 2D Matrix (LeetCode 74), a medium problem from the 2D Matrix pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Each row continues where the previous one ended, so the whole matrix is one sorted list in disguise. Binary search over indices 0..m·n−1 and convert each index to (row, col) = (i // n, i % n).

Approach

  1. 1

    low = 0, high = m·n − 1.

  2. 2

    mid → row = mid // n, col = mid % n.

  3. 3

    Standard binary-search comparisons.

How I solved it

Flattened binary searchPythonO(log mn) time
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        #represent 0 to m*n-1 list/array
        m = len(matrix)
        n = len(matrix[0])
        low = 0
        high = m*n-1
        while low<=high:
            mid = (low+high)//2
            row = mid//n
            col = mid%n
            if matrix[row][col]==target:
                return True
            elif matrix[row][col]>target:
                high = mid-1
            else:
                low = mid+1
        return False
Loading the step-through…

Search a 2D Matrix — FAQ

What is the intuition behind Search a 2D Matrix?

Each row continues where the previous one ended, so the whole matrix is one sorted list in disguise. Binary search over indices 0..m·n−1 and convert each index to (row, col) = (i // n, i % n).

How do you solve Search a 2D Matrix (LeetCode 74)?

1. low = 0, high = m·n − 1. 2. mid → row = mid // n, col = mid % n. 3. Standard binary-search comparisons.

What is the time and space complexity of Search a 2D Matrix?

Time: O(log(m·n)). Space: O(1). (Accepted approach: Flattened binary search.)

What are common mistakes in Search a 2D Matrix?

Divide by the number of columns, not rows.