Skip to content
LC-0074 Medium LeetCode

74. Search a 2D Matrix

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 52% Topics: Array, Binary Search, Matrix
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(logm + logn)
# Space: O(1)

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False

        m, n = len(matrix), len(matrix[0])
        left, right = 0, m * n
        while left < right:
            mid = left + (right - left) / 2
            if matrix[mid / n][mid % n] >= target:
                right = mid
            else:
                left = mid + 1

        return left < m * n and matrix[left / n][left % n] == target


Solution from kamyu104/LeetCode-Solutions · MIT