Search a 2D Matrix II — LeetCode 240 Python Solution

MediumArrayBinary SearchDivide and ConquerMatrix
Problem
#240
Reading time
2 min

The problem

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right.

Example

Input
matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output
true

Python solution

Python
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            j = bisect_left(row, target)
            if j < len(matrix[0]) and row[j] == target:
                return True
        return False

Complexity

MeasureComplexity
TimeO(m \times \log n), where m and n are the number of rows and columns of the matrix, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 240. Search a 2D Matrix II 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 240. Search a 2D Matrix II?
LeetCode 240. Search a 2D Matrix II is rated Medium on LeetCode.
What is the time complexity of LeetCode 240. Search a 2D Matrix II?
The Python solution on this page runs in O(m \times \log n), where m and n are the number of rows and columns of the matrix, respectively.
What is the space complexity of LeetCode 240. Search a 2D Matrix II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 240. Search a 2D Matrix II cover?
LeetCode 240. Search a 2D Matrix II is tagged Array, Binary Search, Divide and Conquer 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.

Get Stealth Interview