An Intro to Space Complexity

A beginner’s guide to assessing an algorithm use of computer memory

What is space complexity?

Space complexity is a way to evaluate how efficiently an algorithm uses computer memory. Although we’re talking about memory — think ‘bytes’ — space complexity is expressed using big-O notation, i.e., how much additional memory is required based on input size.

Any new data structure created during the algorithm's execution is considered new data requiring new or additional memory. Yes, even if the data doesn’t persist beyond the execution of the algorithm. This additional space in memory is called auxiliary space.

Wait, before we go on…

Auxiliary space is the extra space needed by an algorithm to execute.

Examples — What’s the space complexity of the following algorithm?

In the above example, we don’t need to allocate or copy any new data; we modify the given array. No additional data is required, even if the input array is large. Therefore, the space complexity is O(1) because we use a constant amount of space no matter the input size.

The first thing to notice is that this algorithm uses recursion. Why is this important? Well, every time we make a new function call a new stack frame to the stack memory. This means that if n is 100, then the recursion stack will be 100. Therefore, the space complexity is 0(n).

This algorithm has O(1) space complexity because it uses a constant number of variables regardless of the input size.

Using this quadratic algorithm, the space complexity is O(1), as no additional space is required.

Hopefully, this quick introduction to space complexity will help kickstart your journey to demystifying space, time complexity, and big-O notation.

Full-stack developer. Funny-peculiar. Lover of baking, yoga, and reading (between the lines).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store