-1

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!

Hasan S.
  • 17
  • 7
  • Is `n` in the space complexity the problem size or `n` from `nxn`? I would think the later. – Neil Dec 01 '22 at 21:01
  • The space complexity of the function is O(n^2). This is because you are allocating a new 2D array of size (n-2) x (n-2) inside the function. This array will take up O(n^2) space. The input size is n x n, but you are not using any additional space proportional to n. You are using a constant amount of space for the loop variables and a few other constants. Therefore, the space complexity is O(n^2). – Hasan S. Dec 17 '22 at 21:09

1 Answers1

1

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

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Dani
  • 14,639
  • 11
  • 62
  • 110