# Search Sorted Matrix in Linear Time

## Lost time is never found again ⌚

## Statement

We have to search for a value ** x **in a sorted matrix

**. If**

*M***exists, then return its coordinates**

*x***, else return**

*(i, j)***.**

*(-1, -1)*Let us consider the above matrix as an example. In this example, we are going to search for the value **12.** Since 12 is present in the matrix, the algorithm should return its coordinates **(2, 1)**

## Simple Approach

A simple approach is to traverse all the values in the matrix and check if it is equal to 12.

The worst case time complexity of the above algorithm will be

O(n x m) = O(n²)whenn = m

**Efficient Approach**

The above algorithm behaves worse for large values of n and m. Let us look into the efficient algorithm now.

**Algorithm**

```
1. Start from Top Right position (***0, m - 1)*** in the matrix ***M*
**2. If the value is equal to ***x ***return ***(0, m - 1)
***3. Move one row down if the current value is less than ***x
***4. Move one column left if the current value is greater than ***x***
```

Let us apply this algorithm into our matrix ** M.** We are going to search for the value

**12**in

*M**Step 1 and 2*

Start from the Top Right value

**5**atis less than 12, so 12 should be somewhere in the bottom of the matrix since all row and column values are sorted in ascending order. So we move one row down.*M*[0][4]. 5The value

**10**atis also less than 12, so we move one row down.*M*[1][4]

*Step 3 and 4*

The value

**15**atis greater than 12, so 12 should be somewhere in the left of the matrix, so we move one column left.*M*[2][4]The value

**14**atis also greater than 12, so we move one column left*M*[2][3]

*Step 5 and 6*

The value

**13**atis greater than 12, so we move one column left*M*[2][2]The value at

is equal to 12, so we return its index*M*[2][1]**(2, 1)**The worst case time complexity of the above algorithm will be

**O(n + m) = O(2n) = O(n)**when**n = m, ***because we will be iterating all rows and all columns once ifis at the bottom left position*x***(n - 1, 0)*

You can find the Java solution for this algorithm in the Github repo.
**ganeshkumarm1/DSAlgo**
*A Curated list of Data Structures and Algorithms implemented in Java.*github.com

## Thank you 🤘

To know more about me, visit ganeshkumarm.me