LeetCode 0074. Search a 2D Matrix Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0074. Search a 2D Matrix

Description

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.

Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

 

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

Solutions

Solution 1: Binary Search

We can logically unfold the two-dimensional matrix and then perform binary search.

The time complexity is O(log(m × n)), where m and n are the number of rows and columns of the matrix, respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScript
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(code-box)

Solution 2: Search from the Bottom Left or Top Right

Here, we start searching from the bottom left corner and move towards the top right direction. We compare the current element matrix[i][j] with target:

  • If matrix[i][j] = target, we have found the target value and return true.
  • If matrix[i][j] > target, all elements to the right of the current position in this row are greater than target, so we should move the pointer i upwards, i.e., i = i - 1.
  • If matrix[i][j] < target, all elements above the current position in this column are less than target, so we should move the pointer j to the right, i.e., j = j + 1.

If we still can't find target after the search, return false.

The time complexity is O(m + n), where m and n are the number of rows and columns of the matrix, respectively. The space complexity is O(1).

PythonJavaC++GoRustJavaScript
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m, n = len(matrix), len(matrix[0]) i, j = m - 1, 0 while i >= 0 and j < n: if matrix[i][j] == target: return True if matrix[i][j] > target: i -= 1 else: j += 1 return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !