MediumNo. 0074

Search a 2D Matrix — LeetCode 74 Python Solution

Topics
Array, Binary Search, Matrix
Reading time
2 min

The problem

You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row.

Example

Input
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output
true

Python solution

PythonSolution
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        left, right = 0, m * n - 1
        while left < right:
            mid = (left + right) >> 1
            x, y = divmod(mid, n)
            if matrix[x][y] >= target:
                right = mid
            else:
                left = mid + 1
        return matrix[left // n][left % n] == target

Complexity

Time
O(log(m × n))where m and n are the number of rows and columns of the matrix, respectively
Space · auxiliary
O(1)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 74. Search a 2D Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 74. Search a 2D Matrix?

LeetCode 74. Search a 2D Matrix is rated Medium on LeetCode.

What is the time complexity of LeetCode 74. Search a 2D Matrix?

The Python solution on this page runs in O(log(m × n)), where m and n are the number of rows and columns of the matrix, respectively.

What is the space complexity of LeetCode 74. Search a 2D Matrix?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 74. Search a 2D Matrix cover?

LeetCode 74. Search a 2D Matrix is tagged Array, Binary Search and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.