Search a 2D Matrix

Program for Search in a row wise and column wise sorted matrix Problem

You are given a 2D array called matrix with m rows and n columns, and a number called target.

  • Each row in the matrix is sorted in increasing order.
  • The first number of each row is larger than the last number of the row before it.

Your task is to check if the target is present in the matrix. Return true if it’s found, otherwise return false. The solution should search efficiently in O(log(m * n)) time, similar to binary search in a sorted list.

Search a 2D Matrix Problem

Example 1

Example 1 Search 2D Matrix

Example 2

Example 2 Search 2D Matrix

Constraints:

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

Program for Search in a row wise and column wise sorted matrix Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(log(m * n)) time and O(1) space, where m is the number of rows and n is the number of columns in the matrix.

Hints for solving problems

Hint 1 :

A brute force solution would be to do a linear search on the matrix. This would be an O(m * n) solution. Can you think of a better way? Maybe an efficient searching algorithm, as the given matrix is sorted.

Hint 2 :

We can use binary search, which is particularly effective when we visualize a row as a range of numbers, [x, y] where x is the first cell and y is the last cell of a row. Using this representation, it becomes straightforward to check if the target value falls within the range. How can you use binary search to solve the problem?

There are mainly 4 approach to solve this problem-

  1. Brute Force Method
  2. Staircase Search Method
  3. Binary Search Method
  4. Binary Search(One Pass) Method

1. Brute Force Method

Iterate through every element in the matrix and compare it with the target until a match is found.

  • Time complexity: O(m*n)
  • Space complexity: O(1)

where m is the number of rows and n is the number of columns of matrix.

Code

2. Staircase Search Method

Start from the top-right or bottom-left corner, move left if the target is smaller, or move down if the target is larger.

  • Time complexity: O(m+n)
  • Space complexity: O(1)

where m is the number of rows and n is the number of columns of matrix.

Code

3. Binary Search Method

Treat the 2D matrix as a flattened 1D array and apply binary search by calculating mid-row and mid-column indices.

  • Time complexity: O(log m + log n)
  • Space complexity: O(1)

where m is the number of rows and n is the number of columns of matrix.

Code

4. Binary Search(One Pass) Method

Perform binary search directly on the matrix using row and column calculations in a single pass, avoiding flattening.

  • Time complexity: O(log (m*n))
  • Space complexity: O(1)

where m is the number of rows and n is the number of columns of matrix.

Code

More Articles