Checkpoint 15.3.1.
Example 1: Find the time complexity of this program. Be careful of the nested loop.
def example_func(n):
for i in range(n):
for j in range(n):
print(i * j)
-
O(1) - Incorrect; we have two nested loops here.
-
O(logn) - Not quite. You typically see
O(logn)more often in search/sort algorithms. -
O(n) - Incorrect; both loops (one of which is nested) depend on n.
-
O(n^2) - Correct! Both loops depend on n, and one loop is nested, which multiplies it by the parent factor.
