Question presented to candidate: "We talk a lot about time complexity. What is space complexity? And if I write a recursive function in Python, how much memory does the recursion itself use โ for example for a recursive sum, a recursive binary search and naive Fibonacci?"
What a strong answer should cover:
- Space complexity is how extra memory grows with n; distinguish auxiliary space (extra) from total space (including the input), and say whether the output counts.
- Each active call occupies a stack frame, so recursion costs O(maximum recursion depth) stack space โ not O(number of calls).
- Worked examples: recursive sum O(n) stack, recursive binary search O(log n), naive Fibonacci O(2โฟ) time but O(n) stack, DFS O(height).
- Converting deep recursion to a loop or an explicit stack, and in-place algorithms with O(1) extra space.
- Python specifics: the default recursion limit of 1000 (
RecursionError), no tail-call elimination in CPython, and slicing (nums[1:]) copying memory at every level.
Code / implementation expected: Yes โ a recursive function and its iterative or explicit-stack rewrite in Python, with the stack depth stated.