VOOZH about

URL: https://www.geeksforgeeks.org/dsa/search-in-matrix-where-only-individual-columns-are-sorted/

⇱ Search in matrix where only individual columns are sorted - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Search in matrix where only individual columns are sorted

Last Updated : 23 Jul, 2025

Given an n * m semi-sorted 2D matrix, mat[][] where each column is individually sorted in ascending order but the rows are not sorted, and a target element x. The task is to find the position (row and column index) of x in the matrix. If the element is not found, return -1.

Examples: 

Input: mat[][] = [[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
x = 5
Output: (1, 1)
Explanation: Element 5 is present in the matrix at row index 1 and column index 1.


Input: mat[][] = [[10, 20, 30],
[15, 25, 35],
[18, 28, 40]]
x = 26
Output: -1
Explanation: Element 26 is not found in any column of the matrix, so the output is -1.

[Naive Approach] - O(n*m) Time and O(1) Space

We linearly scan each element of the matrix and compare it with the target x, moving through every row and column since there is no row-wise order.
For detailed explanation and code please refer Searching Algorithms for 2D Arrays (Matrix).

[Expected Approach] Using Binary Search - O(m*log(n)) Time and O(1) Space

The idea is to leverage the sorted property of each column in the matrix. Since each column is individually sorted, we can apply binary search column-wise to speed up the search which is more efficient than linear search.


Output
(1, 1)
Comment