Explain space complexity


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


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.


You must go-through on this link for better understanding of space complexity


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).