![]() |
VOOZH | about |
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.
Table of Content
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).
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.
(1, 1)