What is the time complexity of traversing (rows ,columns) a two dimensional array?
bool check(int array [9][9])
{
int num=0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (array [i][j] == 0) {
num++;
}
}
}
return num;
}
I think each for loop
will take square root of n
so that nested loops totally take O(n)
as traversing all elements, where I am defining n
as the total size of the input (in this case 81 elements in array
). Is that correct?
n
in your case? The code shows the array of sizes9
. If, actually, you work with NxN array the complexity is O(N**2). And, please, format your code – Plattern == N*N
where N is a size of an each array as well as the number of arrays, thenO(N**2) == O(n)
; however, IMHO, the parametern
as it defined (n == N*N
) is quite strange. – PlatterO(N*M)
and for a good reason: many algorithms are unsymmetric. – AsdicO()
represented as a square and not linear? IsO()
dependent on the shape of the input data structure? – WychelmO(n)
you really mean that the amount of work grows linear while the total number of elements in array grows linear. Usually it's much less useful thanO(n*m)
but it's correct as long as you really understand what you say. – Asdic