I need to write a method that takes 2d array 'int [][] m' and a value 'val' and check if val is in the array in the complexity of O(n) while n defined as the number of rows and m must be squared
The array that can use as a parameter for my method must return true for this method:
(if it returns true so the array is as requested)
public static boolean test(int[][] m) {
int n = m.length;
for (int r = 0; r < (n - 1); r++)
for (int c = 0; c < n; c++)
for (int i = 0; i < n; i++)
if (m[r][c] > m[r + 1][i]) return false;
return true;
}
This array returns TRUE:
int [][] arr3 = new int [][]{
{ 0, 2, 1, 2, 0, 5, 5, 5, },
{ 21, 21, 7, 7, 7, 21, 21, 21 ,},
{ 21, 21, 21, 21, 21, 21, 21 , 21, },
{ 21, 21, 23 , 42, 41, 23, 21, 21, },
{ 60 ,56, 57, 58, 53, 52, 47, 51 ,},
{ 61, 65, 70 , 72, 73, 78, 82, 98 ,},
{ 112, 121, 112, 134, 123, 100, 98, 111,},
{ 136, 136, 136, 134, 147, 150, 154, 134,},
};
My method should return true if val
is in the array and looks like this:
public boolean findValTest(int [][] m, int val){...}
your solution is here. i made a function that do binary search for first column. if the val find in the first column the function return true, else last period of 'l' and 'r' are benefit for us. 'r' and 'l' are always equal of have only one distance(r=l or abs(r-l)=1 ). lower bound of 'r' and 'l' are expected row that the val maybe exist in it. so we should search this row.
O(n) for binary search is Log(n) and for row search is n. so the final O(n) will be n.code is here:
It is possible iff. the matrix
m
is a square matrix of size n x n. Core idea is inspired by oleg.cherednik's answer. As soon as we find arow
inm
, such thatm[row][0] >= val
, we know thatval
must be in either rowrow
orrow - 1
(since the same comparison onrow - 1
wasfalse
). Thus, we have to find our candidate rows (O(n)) and then analyze only those two rows (also O(n)). Ifm
is not square, but rectangular, the algorithm has a complexity of O(n + k), where n is the number of rows and k is the number of colums inm
. This leads to the following algorithm.We can improve the acutal runtime by determining the candidate lines through a binary search algorithm so that candidate lines are found in O(log(n)) instead of O(n). The asymptotical runtime will still be O(n) for square matrices and O(log(n) + k) for non-square n x k matrices. The idea for this was taken from Saeed Bolhasani's answer.
Smth. like that. In case of Every number at row
i
is equals or smaller then every number on rowi+1
, than you can check only first element in each row to define a row, where required value could be. Element in unsorted row can be found only with full scan.This algorithm have to scan 2 full rows only, which is O(n) where n - number of rows.
Test cases: