Space Complexity: Measure your Code Performance | DSA 002
2 min read
In my previous article I wrote about time complexity. A way to measure code with respect to growing size of inputs.
Time complexity is basically the relation between input size and running time
Think About It
You obviously have apps in your phone. You are most likely to prefer the ones which takes less time to load the data and consumes less space. The factor which is used to measure the time is related to time complexity. But what about the space? How do we measure the space used by a code?
The relation between the input size and memory consumed in your system.
If you want your code to be optimized, it should take less time and less space too. So, here's where space complexity comes in place cause this is the way to measure how much space your code will take
Calculating Space Complexity
The space used by a code depends on how many variables are used. The more variables, the more space used.
How much memory consumed by a code is directly proportional to how many variables assigned
sum = 0 i = 0 while (i < 24): sum += i i += 1 print(sum)
Here, there are 2 variables which we are assigning to the memory that is
sum. Now, no matter the the value of sum increases the memory used by that one variable would be the same. So, the space complexity for this code will be O(1)
Now, let's take the example of arrays. It is basically a data structure which stores a list of elements. We will talk about arrays deeply later
def create_array(n): a =  for i in range(n): a.append(i) return a
In this function, we take integer
n as an input. Then we create an array. Using the loop we store the numbers 0 to n-1 in the array. Then we return it. So, basically what we are doing is, we are generating a series of numbers and storing it in an array. Here, with the increasing size of input, the space used by the code also increases. So, the space complexity for this code is O(n)
You can check the size here:
sys.getsizeof() gives out the size of a particular function, class, variable etc. in python
I really hope you understood, if you didn't then feel free to criticize in the comment section. It's okay to criticize if I have wasted your valuable time. Also if you have any doubts, feel free to put it up in the comments section