A 3d matrix sorted in all three dimensions is given and we have to find a given number in it.
For the above problem, I have been thinking this: The 3D array arr[m][n][r]
would be like a stack of rectangles where each rectangle (consider arr[m][n][0]
) would have the largest element as the lowest right-most element(arr[m-1][n-1][0]
). We can search inside each rectangle in O(m+n)
:
int row = 0;
int col = N-1;
while (row < M && col >= 0)
{
if (mat[row][col] == elem)
{
return true;
}
else if (mat[row][col] > elem)
{
col--;
}
else
{
row++;
}
}
I was thinking it could be similarly extended to the 3rd dimension , hence making it a linear complexity solution(O(m+n+r)
). Am I right ?
Does anyone have any other ideas? What would be the complexity?