π§³ Space Complexity¶
Space complexity describes how much extra memory an algorithm uses as input grows.
Important idea: distinguish between:
- input space (the data you already have)
- auxiliary space (extra memory the algorithm allocates)
β Common Space Patterns¶
- Building a new list of size
nβO(n)extra space - Using a few variables β
O(1)extra space - Recursion adds call stack frames β often
O(depth)
β Generators vs Lists¶
squares_list = [x * x for x in range(1_000_000)] # stores everything
squares_gen = (x * x for x in range(1_000_000)) # computes one at a time
Generators often reduce memory usage because they donβt store all results at once.
π Key Takeaways¶
- Favor in-place operations when safe.
- Prefer generators for streaming data.
- Remember recursion uses stack memory.