Search in a Sorted Matrix

5

1 votes
Problem

You are given an N * N matrix of integers where each row and each column is sorted in increasing order. You are given a target integer 'X'. Find the position of 'X' in the matrix, if it exists then return the pair {i, j} where 'i' represents the row and 'j' represents the column of the array, otherwise return {-1,-1}

Input Format:

The first line of input contains a single integer 'T', representing the number of test cases or queries to be run. Then the 'T' test cases follow. The first line of each test case contains two space-separated integers 'N' and 'X', representing the size of the matrix and the target element respectively. Each of the next 'N' lines contains 'N' space-separated integers representing the elements of the matrix.

Output Format:

For each test case, print the position of 'X', if it exists, otherwise print “-1 -1”.

Important Note:

You must write an algorithm with time complexity less than O(n2) and space complexity should be O(1).Two nested for loop solution will not be allowed.

Constraints:

1 ≤ T ≤ 10

1 ≤ N ≤ 103

1 ≤ X ≤ 106

1 ≤ Aij ≤ 106

where 'T' is the number of test cases, 'N' is the number of rows and columns, 'X' is the target value, and Aij is the elements of the matrix.

 

 

 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The first test case,the given matrix is:[ [1, 2, 5], [3, 4, 9], [6, 7, 10]] We have to find the position of 4. We will return {1,1} since A[1][1] = 4.

The second test case, the given matrix is: [[4, 5], [5, 6]] We have to find the position of 5. So we return {0,1}.

Editor Image

?