Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
1-check the first element of the each row if first element is greater than the item to be searched ignore that row.
2-check the last element of each row if it is less than item to be searched ignore this row also.
do 1 and\or 2 for every row and after that apply the binary search on remaining row.
@Maxximus, @Kuldeep
Your estimate for time complexity is wrong. Its still O(nlogn). Filtering rows on basis of range does not guarantee that the number of valid rows will be very small compared to n. You can easily imagine a matrix for which n=1000000 and number of invalid rows = 100. In these cases, even after filtering the number of rows is O(n) and for each row a binary search means O(logn) time for that row. Thus, it still comes out O(nlogn).
The matrix is sorted row-wise also means you consider the elements in each column, they are also sorted top down. So, we can first perform a binary search on say the first column, reach a particular row and then perform another binary search on the row to get to the required element.
For a MxN matrix, this solves the problem in O(log M) + O (log N)
You just need to search the required row !!
First of all, according to the problem statement, the columns are unsorted. So this solution is clearly out.
Second of all, that wouldn't work even if the columns were sorted. Think about it: just because you know that the element is > arr[k][0] and < arr[k+1][0], for some k, doesn't mean the element is positioned somewhere like arr[k][i], for some i. The element could be at arr[0][j] for some j, for example.
Yes eugene. That's correct. This works only for the case where the elements are sorted row wise and also column wise. Basically I meant I have some completely sorted matrix as we go through the rows down the matrix. Sorry I missed the explicitly stated point that the elements are not sorted column-wise
Create a one dimentional sorted array outofit which can be done in o(n) time
Now searching for an element in this wll take o(logn). This will give us o(n) + o(logn) time i.e. o(n) time. Please let me know if i am wrong here
We need to use matrix properties in this ques. start from any element in the matrix and compare with elements which is around that element, then move your pointer to the element which is more close to it then again repeat the process until you find the element.
Perform Binary search in each and every row. I think this is optimal with complexity O(n log n)
- Anonymous October 01, 2012