Solution is O(log(m) + log(n)) but still shows TLE. Please point out error in my code

Tags: #<Tag:0x00007f182ccf6188>

#1
``````
int search2d(vector<vector > matrix, int r_low, int c_low, int r_high, int c_high, int ele) // Ignore <vector part
{
while(r_low<=r_high)
{
int r_mid = r_low + (r_high-r_low)/2;
if(matrix[r_mid][c_low] <= ele && matrix[r_mid][c_high] >= ele)
{
r_low = r_mid;
break;
}
else if(matrix[r_mid][c_high] < ele)
{
r_low = r_mid + 1;
}
else if(matrix[r_mid][c_low] > ele)
{
r_high = r_mid - 1;
}
}
if(r_low>r_high)
return 0;
while(c_low<=c_high)
{
int mid = (c_low + c_high)/2;
if(matrix[r_low][mid]==ele)
return 1;
else if(matrix[r_low][mid] > ele)
c_high = mid - 1;
else if(matrix[r_low][mid] < ele)
c_low = mid + 1;
}
return 0;
}
```
```

where,
matrix = A
r_low = 0
c_low = 0
r_high = m-1
c_high = n-1

#2

Check your first while’s break condition, if you reach the row where is the target you have to break the iteration, i mean if r_lo==r_hi that means that you find the row where the target should be or where the target “could” be.
And also when you update the r_high, you are discarding the option where matrix[r_mid][c_low] is greater than “ele” but “ele” is in the same row some positions behind, so this causes a for ever loop.