Skip to content
Ultimate Algorithm

Space Complexity

What is Space Complexity?

Space Complexity is amount of memory space required to run an algorithm

Let’s see some examples here too.

Question 1
# Returns sum of the array
def get_sum(nums):
    total_sum = 0

    for n in nums:
        total_sum += n
    
    return total_sum
Answer
O(1)
We don't need additional memory space other than the variable called total_sum which is constant regardless of the size of the input coming(nums size)

Question 2
# Returns 2D Array based on input
def create_matrix(n):
    matrix = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(0)
        matrix.append(row)
    return matrix 
Answer
O(N^2)
Based on the input n, the code needs n^2 additional space for creating returned matrix.