← All Complexity Drills

Complexity Analysis

#29 — Traps & Gotchas

def remove_all(arr, val):
    while val in arr:
        arr.remove(val)
    return arr

What is the time and space complexity?

Work it out before scrolling down.

Time

O(n²)

Space

O(1)

How to derive it

Trap: both `val in arr` and `arr.remove(val)` are O(n) each. If val appears k times, the while loop runs k times, each iteration doing O(n) work → O(k × n). Worst case k = n (all elements equal val), giving O(n²). A single-pass filter `[x for x in arr if x != val]` would be O(n).

← #28 #30 →