so far , we’ve been focusing on time complexity how can we analyze the runtime of an algorithm as the size of the inputs increases ?
We can also use big O notation to analyze space complexity: how much additional memory do we need to allocate in order to run the code in our algorithm
Space Complexity in JS
Example
function sum(arr){
let total = 0;
for (let i = 0; i < arr.length;i++){
total += arr[i];
}
return total;
}
time complexity - O(n)
space complexity- O(1)
function double(arr){
let newArr = [];
for(let i = 0; i < arr.length; i++){
newArr.push(2 * arr[i]);
}
return newArr;
}
space complexity - O(n)