LeetCode 74. Search a 2D Matrix

Description

https://leetcode.com/problems/search-a-2d-matrix/

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

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

Example 2:

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

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

Explanation

Use binary search to find which row the target potentially locates. Then also use binary search to search those potential rows.

Python Solution

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        start = 0
        end = len(matrix) - 1
        
        
        while start + 1 < end:
            mid = start + (end - start) // 2
            
            if matrix[mid][0] == target:
                return True            
            elif matrix[mid][0] > target:
                end = mid
            else:
                if self.binary_search(matrix[mid], target):
                    return True
                
                start = mid
                
        if self.binary_search(matrix[start], target) or self.binary_search(matrix[end], target):
            return True
        
        return False
    
    def binary_search(self, nums, target):
        start = 0
        end = len(nums) - 1

        while start + 1 < end:
            mid = start + (end - start) // 2                

            if nums[mid] == target:
                return True        
            elif nums[mid] > target:
                end = mid
            else:
                start = mid

        if nums[start] == target or nums[end] == target:
            return True
        
        return False
  • Time Complexity: O(log(N)).
  • Space Complexity: O(1).

Leave a Reply

Your email address will not be published.