Given an M × N matrix, which is row-wise and column-wise sorted (with all strictly increasing elements in any row or column), report all occurrences of a given element in it in linear time.

For example,

Input:
 
[ -4 -3 -1  3  5 ]
[ -3 -2  2  4  6 ]
[ -1  1  3  5  8 ]
[  3  4  7  8  9 ]
 
Output:
 
Element 3 is found at position (0, 3)
Element 3 is found at position (2, 2)
Element 3 is found at position (3, 0)

Practice this problem

We can do a binary search to find an index of the first occurrence and the last occurrence of the given key for each row. The complexity of this solution will be O(M × log(N)), which is not linear as per problem time constraints.

 
The idea is to take advantage of the fact that the matrix is row-wise and column-wise sorted. We start from the matrix’s top-rightmost cell and do the following until the matrix boundary is reached:

  1. If the current element is less than the key, increment the row index (move to the next row)
  2. If the current element is more than the key, decrement column index (move to the previous column)
  3. If the current element is equal to the key, print the current location and increment row index & decrement column index to find the key’s next location in the given matrix. This will work as the matrix contains all strictly increasing elements in any row or column.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Element 3 is found at position (0, 3)
Element 3 is found at position (2, 2)
Element 3 is found at position (3, 0)

The time complexity of the proposed solution is O(M + N) for an M × N matrix and doesn’t require any extra space.