Skip to the solution
EasyDSA9 min read

What is space complexity, and how much stack space does recursion use?

738 views

The problem

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.

  • dsa
  • complexity
  • recursion
  • space

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMeasure the call-stack depth of recursive and iterative code
PythonO(1) vs O(n) extra space, and replacing recursion with an explicit stack

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 18 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you move all zeroes to the end of an array in place?

Continue