Space complexity

Space complexity refers to the amount of memory an algorithm needs to run to completion. The need for space can be attributed to variables, data structures, function calls, and allocations, etc.

To determine space complexity, we consider both the fixed space requirements and the variable space requirements.

  1. Fixed Space Requirements: This is independent of the size of the problem, i.e., the space needed for simple variables and constants involved in the procedure, fixed-size variable attributes, and so on.
  2. Variable Space Requirements: This is the space needed by variables, whose size depends on the size of the problem. It includes space needed by variables, arrays, structures, etc. that are dynamically created.

The total space requirement is the sum of these two types of space requirements.

For example, consider the following function:

def sum(n):
    if n <= 0:
        return 0
    else:
        return n + sum(n-1)

The space complexity of the above function is O(n). This is because at any time, there are “n” recursive calls on the stack, so the amount of memory used is proportional to “n”.

To reduce space complexity, we often use iterative solutions where possible, as they have lower overhead than recursive functions. In some cases, a slightly slower algorithm can actually be beneficial if it uses significantly less memory, particularly for large data sets.

To calculate space complexity, you should understand the data structures you’re using, the input size, and how they’re implemented.

Calculating Space Complexity
  1. Consider Variables and Data Structures: Note all the variables and data structures used in the algorithm.
  2. Count the Memory Usage: Estimate how the memory usage scales with input size.
  3. Formulate Space Complexity: Express this in Big O notation.

Hello, Iā€™m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ā¤ļø

Feedback Display Feedback Display