VOOZH about

URL: https://www.geeksforgeeks.org/dsa/search-in-row-wise-and-column-wise-sorted-matrix/

⇱ Search in a row wise and column wise sorted matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Search in a row wise and column wise sorted matrix

Last Updated : 23 Jul, 2025

Given a matrix mat[][] and an integer x, the task is to check if x is present in mat[][] or not. Every row and column of the matrix is sorted in increasing order.

Examples:

Input: x = 62, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: false
Explanation: 62 is not present in the matrix.

Input: x = 55, mat[][] = [[18, 21, 27],
[38, 55, 67]]
Output: true
Explanation: mat[1][1] is equal to 55.

Input: x = 35, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: true
Explanation: mat[2][0] is equal to 35.

[Naive Approach] Comparing with all elements - O(n*m) Time and O(1) Space

The simple idea is to traverse the complete matrix and search for the target element. If the target element is found, return true. Otherwise, return false.


Output
true

[Better Approach] Binary Search - O(n*logm) Time and O(1) Space:

To optimize the above approach we are going to use the Binary Search algorithm.
The problem specifies that each row in the given matrix is sorted in ascending order. Instead of searching each column sequentially, we can efficiently apply Binary Search on each row to determine if the target is present.


Output
true


[Expected Approach] Eliminating rows or columns - O(n + m) Time and O(1) Space:

The idea is to remove a row or column in each comparison until an element is found. Start searching from the top-right corner of the matrix. There are 3 possible cases:

  1. x is greater than the current element: This ensures that all the elements in the current row are smaller than the given number as the pointer is already at the right-most element and the row is sorted. Thus, the entire row gets eliminated and continues the search from the next row.
  2. x is smaller than the current element: This ensures that all the elements in the current column are greater than the given number. Thus, the entire column gets eliminated and continues the search from the previous column, i.e. the column on the immediate left.
  3. The given number is equal to the current number: This will end the search.

Illustration:



Output
true


Related Article: Search element in a sorted matrix

Comment