DSA · Patterns, not puzzles
What is the difference between time and space complexity?
Short answer
Time complexity measures how runtime grows; space complexity measures how extra memory grows. Techniques like memoization trade more space for less repeated work.
Time and space are separate budgets. An algorithm can be fast but use a lot of memory, or use very little memory but recompute the same values repeatedly. Interviewers care about both because production systems have limits on latency and on memory.
function fibRecursive(n) {
if (n <= 1) return n;
return fibRecursive(n - 1) + fibRecursive(n - 2);
}
function fibMemo(n, memo = new Map()) {
if (n <= 1) return n;
if (memo.has(n)) return memo.get(n);
const value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.set(n, value);
return value;
}How to talk about the trade-off
- Count extra space, not the input itself, unless the input is copied
- Recursion uses stack space proportional to call depth
- Hash maps and DP tables use memory proportional to their entries
- In-place algorithms save space but may mutate the input
A useful answer names the bottleneck and the constraint. If memory is tight, prefer an in-place approach or a rolling window of values. If latency is the priority, caching or precomputation may be worth the memory.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the space complexity of recursive Fibonacci?
- 2When would you choose the slower algorithm with less memory?
- 3Does recursion count toward space complexity?
- 4How does memoization change both time and space?
Say it in the interview
Time complexity is how runtime grows with input size, and space complexity is how extra memory grows. They are separate budgets. Recursive Fibonacci is exponential in time but only linear in stack depth, while memoization makes it linear in both time and stored values. I decide based on whether the system is constrained by latency or memory, and I state which one I am optimizing.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.