Search in a row wise and column wise sorted matrix

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

Problem :

Given row wise and column wise sorted matrix ,we need to search element with minimum time complexity.

Solution :

Solution 1:

You can simply search an element in 2D matrix but it will be done in O(R*C) complexity.

Solution 2:

  • Iterate over each row
  • Do binary search on rows unless you find the element.
  • If you do not find the element , return false.

Time complexity : O(C*logR)

Solution 3:

We will use below logic to search an element

  • Elements right to current element will be greater than element
  • Elements left to current element will be lesser than element
  • Elements down to current element will be greater than element
  • Elements top to current element will be lesser than element
Algorithm:
  • Starts with top right element, so initialise r=0 and c=
    sortedMatrix[0].length-1
  • Iterate over matrix with boundary conditions.
  • If current element lets say m is equal to element X, return it.
  • If m < X, go left,so decrease column by 1 (c--).
  • If m > X, go right, so increase row by 1(r++).
Time complexity : O(R+C)

Java program to Search in a row wise and column wise sorted matrix:

When you run the program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *