Can you please explain what is Big O in this example of code?
JavaScript
x
15
15
1
arr = [
2
[1, 1, 1, 1, 1],
3
[1, 1, 1, 1, 1, 1],
4
[1, 1]
5
]
6
7
def count_ones(outer_array):
8
count = 0
9
for inner_array in outer_array:
10
for number in inner_array:
11
count += 1
12
return count
13
14
count_ones(arr)
15
Advertisement
Answer
It depends entirely on your definition of n
. If you define n
to be the number of cells in the 2d matrix, then this nested loop is of linear complexity O(n)
in relation to it.
On the other hand, if you define n
to be the length of the outer array and m
the maximum length of the inner arrays then the time complexity is O(n*m)
.
Either way, the complexity can’t be O(n^2)
since in that case it needs to be a square matrix with sides of equal length n
.