← All Complexity Drills

Complexity Analysis

#6 — Nested Loops

def process(a, b):
    for x in a:
        print(x)
    for y in b:
        print(y)

What is the time and space complexity?

Work it out before scrolling down.

Time

O(a + b)

Space

O(1)

How to derive it

Two sequential loops over different inputs. First loop is O(a), second is O(b). You can't simplify to O(n) because the inputs are independent — if a = 1 million and b = 5, it matters. Always use separate variables for independent inputs.

← #5 #7 →