Search code examples
algorithmspace-complexityarray-algorithms

What is the Space complexity of initializing 2D array in a function that receive 2D array as input?


I was solving a leetcode problem , and wanted to find the space complexity[1] of a function that receives a 2D array of size nxn, and in the function I initialize a new 2D array of size (n-2)x(n-2)

Here is the code

/**
 * @param {number[][]} grid
 * @return {number[][]}
 */
var largestLocal = function(grid) {


    // declare (n-2 x n-2) matrix
   const matrix = new Array(grid.length -2).fill(0)
                .map(() => new Array(grid[0].length-2).fill(0));
    


    for (let i=0; i< grid[i].length -2 ; i++){
        for(let j=0; j<grid.length -2 ;j++){

            //find the max in each 3x3 martix
            matrix[i][j] = Math.max( 
                grid[i][j],     grid[i][j+1],   grid[i][j+2],
                grid[i+1][j],  grid[i+1][j+1],  grid[i+1][j+2],
                grid[i+2][j],  grid[i+2][j+1],  grid[i+2][j+2]
                );
            
        }
    }

    return matrix;
};

Now am confused is the space complexity considered O(n) since same size of the input or O(n 2 ) ?

[1] Space Complexity : Space complexity is a function describing the amount of memory (space) an algorithm takes in terms of the amount of input to the algorithm. We often speak of "extra" memory needed, not counting the memory needed to store the input itself.

I guess its O(n) because the complexity level of the function still the same as input!


Solution

  • it is O(n^2) the number of "memory" cell that you will create eventually will be (n-2)(n-2) which is n^2 -4n + 4 which is... n^2