I had to write a code (as an exercise) that receives a 2D row wise and col wise sorted array and an element, and return true is the element exists in the array.
The first thing that came to mind when i heard "sorted" is binary search, but than i realized that the last element in each row isn't necessarily smaller than the first one in the next line.
So, i figured out that the best complexity will be O(n), and wrote the following code:
public static boolean findN(int[][] a, int x) {
if (a.length == 0 || a[0].length == 0 || x > a[a.length - 1][a[0].length - 1] || x < a[0][0]) {
return false;
}
int LastRow = a.length - 1, Lastcol = a[0].length - 1, row = 0, col = 0;
while (row <= LastRow) {
if (a[row][col] == x) {
return true;
} else if (col < Lastcol) {
col++;
} else {
col = 0;
row++;
}
}
return false;
}
array example:
arr = {{1,2,7,30},
{2,4,18,50},
{3,6,19,90},
{4,7,20,91}}
- After realizing that the best complexity will be O(n), I googled this problem so I'm almost certain that I'm right (although some people are claiming that they can do it in O(log(n))), but am I really?
- Any other thoughts and improvements are welcomed, thank you all in advance!