← All Complexity Drills

Complexity Analysis

#7 — Nested Loops

def nested_different(a, b):
    for x in a:
        for y in b:
            print(x, 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

Outer loop runs len(a) times, inner runs len(b) for each. Total: a × b. This is NOT O(n²) unless a and b are the same size. When loops iterate over different collections, use separate variables.

← #6 #8 →