Intuition : We can solve the question in 1 of 3 ways :
- Using Linear Search (Average approach)
- Using Binary Search to find row to iterate, and then use binary search again to search for element in found row (Better Approach)
- Using Binary Search on whole Array (Best Approach)
Approach 1 of using linear Search is pretty much obvious for anyone to solve on their own.
Approach 2:
- Find rowSize, and colSize.
- To find the row in which our element might lie, just Initialize Start = 0, and end = rowSize-1.
- Calculate mid and compare it with 1 of 3 conditions:
- If x is greater than last element of curRow ( x > arr[mid][colSize-1] ), then update start = mid + 1.
- If x is less than first element of curRow ( x < arr[mid][0] ), then update end = mid - 1;
- otherwise, the x lies in curRow, so break the loop.
- If our loop is broken by our break condition, then our start and end variables satisfies (start ≤ end) condition, if it doesn't, it simply means, that no row exist that contains our targetElement. So return false immediately.
- Now we have row, we can find the targetElement in specific row, using binarySearch.
Approach 3: On carefully analyzing, we can observe that, the whole matrix is sorted, so if we convert the whole matrix into 1D array, giving each element the index from 0 to (n*m) - 1. We will be having the sorted 1D array.
But we won't convert it actually, we will simply assume that each element has index from 0 to (n*m) - 1.
Now if we want to calculate the rowIndex and colIndex for 6th element or index = 5, we just need to reduce the matrix problem into 1D array by asking two questions:
To calculate rowIndex, colIndex of index = 5 or element no. 6th in 1D Array):
- How many full rows will be consumed, if we want to place 5 in our matrix having colSize of 4. We can find it using => index / colSize = 5 / 4 => 1. Meaning the 1 full row will be consumed. So our curIndex would lie in row 2. But, since we follow 0 based indexing, row 2 will be considered as 1. So, we can directly use the 5/4 => 1, as our rowNum.
- What will be my column number, if we want to reduce our curNum in a range from 0 to colSize - 1. We can find it using => index % colSize = 5 % 4 => 1.
So our index 5 or element no. 6th in 1D Array will be on [1][1] index in matrix.
Now we have the way to get rowIndex and colIndex of any element present in our imaginary 1D array. So, we all are smart enought to put binary search to use, to get the search done for target Element.