I am learning about calculating the time complexity of an algorithm, and there are two examples that I can't get my head around why their time complexity is different than I calculated.
After doing the reading I learned that the for-loop with counter increasing once each iteration has the time complexity of O(n) and the nested for-loop with different iteration conditions is O(n*m).
This is the first question where I provided the time complexity to be O(n) but the solution says it was O(1):
function PrintColours():
colours = { "Red", "Green", "Blue", "Grey" }
foreach colour in colours:
print(colour)
This is the second one where I provided the time complexity to be O(n^2) but the solution says its O(n):
function CalculateAverageFromTable(values, total_rows, total_columns):
sum = 0
n = 0
for y from 0 to total_rows:
for x from 0 to total_columns:
sum += values[y][x]
n += 1
return sum / n
What am I getting wrong with these two questions?
total_columnsis explicitly provided as a parameter to the function, and is thus not a constant. The second function is definitelyO(n*m)wherenandmare the number of rows and columns respectively.total_columnsto be "small", because they are typically a handful of "named" variables. However, there is nothing in the problem to suggest thatvaluesisn't some arbitrary matrix, and someone coming from, say, an image processing background would absolutely considertotal_columnsto be an arbitrary variable.valuesmatrix. Then it is indeed O(n).