MediumNo. 0074
Search a 2D Matrix — LeetCode 74 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Binary Search, Matrix
- On study lists
- NeetCode 150 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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] == targetComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0240 | Search a 2D Matrix II | Medium |
| 0363 | Max Sum of Rectangle No Larger Than K | Hard |
| 0378 | Kth Smallest Element in a Sorted Matrix | Medium |
| 0778 | Swim in Rising Water | Hard |
| 1292 | Maximum Side Length of a Square with Sum Less than or Equal to Threshold | Medium |
| 1337 | The K Weakest Rows in a Matrix | Easy |
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.