Source:- What is Space Complexity
For more questions and answers visit our website at Frontend Interview Questions
Space complexity refers to the amount of memory space an algorithm or program requires to execute, and how that memory usage grows as the input size increases. It’s essential to analyze and optimize space complexity to ensure efficient memory utilization. Let’s explore space complexity with some JavaScript examples.
Example 1: Constant Space Complexity O(1)
An algorithm has constant space complexity when the amount of memory it uses remains constant, regardless of the input size.
function add(a, b) {
let result = a + b;
return result;
}
In this example, the `add` function takes two parameters, performs a simple addition, and returns the result. Regardless of the input values, the function uses only a few local variables, and the memory usage remains constant. Thus, the space complexity of this algorithm is O(1), indicating constant space usage.
Example 2: Linear Space Complexity O(n)
An algorithm has linear space complexity when the memory it uses grows linearly with the input size.
function createArray(n) {
let arr = [];
for (let i = 0; i < n; i++) {
arr.push(i);
}…