← All Complexity Drills

Complexity Analysis

#2 — Linear Scans

def sum_and_product(arr):
    total = 0
    for x in arr:
        total += x
    product = 1
    for x in arr:
        product *= x
    return total, product

What is the time and space complexity?

Work it out before scrolling down.

Time

O(n)

Space

O(1)

How to derive it

Two sequential loops, each O(n). Sequential loops add: O(n) + O(n) = O(2n) = O(n). Not O(n²) — the loops are not nested, they run one after another. Two scalar variables = O(1) space.

← #1 #3 →