What is the difference between time complexity and space complexity?
By the Skill-Lync engineering team · Last updated
Answer
Time complexity counts how many basic steps an algorithm takes as input size n grows. Space complexity counts the peak memory it holds as n grows, including the recursion call stack. Both use Big-O notation, and you can often trade one for the other: a hash set finds duplicates in O(n) time using O(n) extra space.
What is the difference between time complexity and space complexity?
Time complexity counts how many basic steps an algorithm takes as the input size n grows. Space complexity counts how much memory it needs at one time as n grows. Both are written in Big-O form, so O(n²) time with O(1) space means steps grow with n squared while memory stays constant.
Both ignore the machine, the language and constant factors, so you can compare algorithms before writing code. The key asymmetry: steps are spent, memory is reused. Time adds up over the whole run, but space is the peak held at any one moment.
| Time complexity | Space complexity | |
|---|---|---|
| Counts | Basic steps: comparisons, additions, calls | Memory cells in use at the same moment |
| Added up as | A total over the whole run | A peak, because freed memory is reused |
| Typical blow-up | Nested loops, naive recursion | Copies of the input, hash tables, deep recursion |
| What goes wrong | Slow response, timeouts | Out of memory, stack overflow, RecursionError |
How do Big-O, Big-Omega and Big-Theta fit in?
Big-O is an upper bound on how fast a function grows, Big-Omega is a lower bound, and Big-Theta is both at once. They describe growth curves, not cases. You can quote any of the three for the best, average or worst case of the same algorithm, and for time or for space.
The formal version, as taught in university algorithms courses (University of Toronto CSC110/111 notes), uses constants that you are free to choose:
Replace $\le$ with $\ge$ and you get $\Omega$. Having both, with two constants $c_1 g(n) \le f(n) \le c_2 g(n)$, gives $\Theta$. Insertion sort shows why the distinction matters. Sedgewick and Wayne's analysis gives about N²/2 compares in the worst case and N−1 in the best case, so its worst case is Θ(n²) and its best case is Θ(n). Saying "insertion sort is O(n²)" is true, but "insertion sort is Θ(n²)" is only true for the worst case. Interviews use "Big-O" loosely for the tight worst-case bound. See What is Big O notation and why is it used? and best, average and worst case.
What is auxiliary space, and is the input counted?
Total space is the memory for the input plus everything the algorithm allocates. Auxiliary space is only the second part: extra arrays, hash tables and call-stack frames. Interviewers usually ask for auxiliary space, because the input exists whichever algorithm you pick.
Sedgewick and Wayne call a sort in place if it uses no extra memory except perhaps a small function-call stack or a constant number of variables. Insertion sort and selection sort qualify, so their auxiliary space is O(1). Merge sort does not: the authors state it uses extra space proportional to N. CPython's design notes say list.sort() (Timsort) can need a temporary array of up to N/2 pointers, and none for input that is already sorted or reversed.
Does the recursion call stack count as space?
Yes. Every active call keeps a frame holding its arguments, local variables and return address, and all the frames alive at once count. A recursive function that never allocates an array can still use O(n) space if it recurses n levels deep.
The figure shows sum(3) written as n + sum(n-1). Four frames are alive at the deepest point, so n = 3 needs n + 1 frames. The loop version needs one running total. CPython caps the depth: sys.getrecursionlimit() returns 1,000 by default, and the Python documentation describes it as the maximum depth of the interpreter stack. That makes recursive space a hard limit in practice, not just a theory score.
Depth, not call count, sets the space. Naive recursive Fibonacci makes 2,692,537 calls for F(30), yet it is never more than 30 frames deep, so its space is O(n) while its time is exponential. Quicksort is the classic interview case. In CLRS problem 7-4, already-sorted input drives the recursion Θ(n) deep, and recursing into the smaller partition first and looping on the larger one brings the depth down to O(log n). See recursion basics for how the base case and the stack interact.
How do three ways to find a duplicate trade time for space?
On 1,024 distinct numbers, nested loops make 523,776 comparisons and use no extra memory. Sorting first takes 10,054 comparisons plus a 1,024-cell buffer. A hash set makes 2,048 set operations and stores 1,024 entries. These are counted by instrumented Python code, not read off a formula.
This is Skill-Lync's worked example for the page. The input is the list (i × 617) mod n for i from 0 to n − 1, a fixed shuffle of 0 to n − 1 with no duplicates, so every method runs to the end (the worst case). Counting rules: one comparison per pair for nested loops; the comparisons inside a top-down merge sort (9,031 at n = 1,024) plus 1,023 neighbour checks for sort-then-scan; one membership test and one insert per element for the hash set. Memory counts elements held, not Python's per-object overhead.
| Method | Time, space | Steps at n = 128 | Steps at n = 1,024 | Growth for 8 times the data | Extra memory at n = 1,024 |
|---|---|---|---|---|---|
| Nested loops | O(n²), O(1) | 8,128 | 523,776 | 64.4 times | 0 cells |
| Sort, then scan | O(n log n), O(n) | 869 | 10,054 | 11.6 times | 1,024 cells + 11 frames |
| Hash set | O(n) average, O(n) | 256 | 2,048 | 8.0 times | 1,024 entries |
Eight times the data cost the nested loops 64 times the work, the hash set 8 times, and the sort a little more than 8 times, matching n² against n against n log n. The catch is that the hash set's O(1) is an average. The Python documentation warns that in the worst case an operation that is normally O(1) takes O(n), and an insert is amortised because the table occasionally resizes. For a handful of items the nested loops are fine and use the least memory. If memory is the constraint, heapsort sorts without needing any extra space (Sedgewick and Wayne), giving O(n log n) time with O(1) auxiliary space.
How do you trade space for time, and time for space?
Spend memory to remember an answer and you stop recomputing it. Memoising Fibonacci cuts F(30) from 2,692,537 recursive calls to 59, at the cost of a 31-entry table. The trade also runs backwards: a loop with two variables needs 29 additions and O(1) space.
| F(30) computed by | Calls or additions | Table entries | Max stack frames | Time, space |
|---|---|---|---|---|
| Naive recursion | 2,692,537 | 0 | 30 | exponential, O(n) |
| Memoised recursion | 59 | 31 | 30 | O(n), O(n) |
| Loop, two variables | 29 | 0 | 0 | O(n), O(1) |
Memoisation saves time because the naive recursion solves the same subproblems again and again. Storing each F(k) once makes the call count 2n − 1. Notice that the memoised version still recurses 30 deep, so it keeps the O(n) stack. Going bottom-up drops both the table and the stack, which is the usual last step of dynamic programming; the Fibonacci optimisation question walks through it. The same pattern appears in the duplicate example: a hash set buys O(n) time with O(n) memory, an in-place sort buys O(1) memory with O(n log n) time.
What are the time and space complexities of common algorithms?
Merge sort runs in Θ(n log n) and needs O(n) extra space, while heapsort and insertion sort need O(1). Binary search takes O(log n) time in O(1) space, a hash lookup is O(1) on average, and BFS or DFS over a graph take O(V + E) time and O(V) space. The table lists more.
| Algorithm | Time | Auxiliary space | Note |
|---|---|---|---|
| Linear search | O(n) | O(1) | n compares when the key is absent |
| Binary search (loop) | O(log n) | O(1) | Sorted input; a recursive version uses O(log n) stack |
| Selection sort | Θ(n²) | O(1) | About n²/2 compares, n exchanges |
| Insertion sort | O(n²) worst, O(n) best | O(1) | Best case n − 1 compares on sorted input |
| Merge sort | Θ(n log n) | O(n) | Between ½ n lg n and n lg n compares |
| Heapsort | O(n log n) | O(1) | Fewer than 2 n lg n compares |
| Quicksort | O(n log n) average, O(n²) worst | O(log n) stack if the smaller side is recursed first | Θ(n) stack depth on bad input otherwise |
Python list.sort() | O(n log n) worst, O(n) if sorted | Up to n/2 pointers | Adaptive |
| Hash set lookup or insert | O(1) average, O(n) worst | O(n) to hold n items | Insert is amortised O(1) |
| BFS or DFS | O(V + E) | O(V) | Visited set plus queue or stack |
| Fibonacci: naive, memoised, loop | exponential, O(n), O(n) | O(n), O(n), O(1) | See the counts above |
Try it: count the steps and the memory
Pick a task, then drag n. The counts come from the same instrumented code as the tables above. Watch which column grows for each method.
Does a list of n distinct numbers contain a duplicate? (worst case: no early exit)
| Method | Steps counted | Extra cells | Stack frames |
|---|---|---|---|
| Nested loopsO(n²) time, O(1) space | 523,776 | 0 | 0 |
| Sort, then scanO(n log n) time, O(n) space | 10,054 | 1,024 | 11 |
| Hash setO(n) average time, O(n) space | 2,048 | 1,024 | 0 |
Bars use a log scale so a million and a thousand can share one row.
Common interview follow-ups
- Does O(1) space mean no memory at all?
- No. It means the memory does not grow with n. A loop with a handful of variables is O(1) whether n is 10 or 10 million.
- Does recursion always cost O(n) space?
- No, the cost is the maximum depth. A recursive binary search is O(log n) deep, merge sort recurses O(log n) deep (plus its O(n) buffer), and naive Fibonacci is n deep even though it makes exponentially many calls.
- Why is a hash set O(1) on average but O(n) in the worst case?
- Lookups are constant when items spread across the table. If many keys collide, an operation may have to walk through most of the stored items, which is the case the Python documentation flags.
- Should I optimise for time or for space?
- Neither wins by default. Find the limit you will hit first: a latency target points to spending memory (caches, hash sets, memoisation), a memory cap or an embedded target points to in-place methods and loops.
Related questions
- What is Big O notation and why is it used?
- Best, average and worst case complexity
- What is recursion and what are its essential components?
- Merge sort and its advantages
- Binary search and its time complexity
- What is dynamic programming?
- All algorithms interview questions
Practise complexity analysis on real code
Skill-Lync's data structures and algorithms course in Java and the Python version take you from Big-O to trees and graphs with code you run yourself. For a quick read, see Skill-Lync's overview of Python data structures and algorithms.
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.