Explain space complexity


#1

i would able to understand time-complexity very well but not have idea about space complexity


#2

You can think of it as “memory” space.
For example, think about “Recursion”. It keeps going down and doing the job until it hit the end. While it keeps going, you need to keep all the results from every previous step, which means you need the spaces for all of them. On the contrary, even though the above questions takes O(n) for each loop but the calculation inside takes only O(1); no need to save any previous result.


#3

You must go-through on this link for better understanding of space complexity
https://www.cs.northwestern.edu/academics/courses/311/html/space-complexity.html


#4

Space complexity is all about variables used in your algorithm. For example if you are adding numbers in a loop and assigning it to a variable. In this case only this variable is used as container/memory for you algorithm. so space complexity would be O(1). In contrast if you are pushing elements inside an array through a loop then every time your container/memory is expanding and the expansion will be directly proportional to number of times loop is running. Hence this will cause space complexity of O(n).