Notation O (NM) or (N ^ 2)

I was told that below code = O (MN), however I came up with O (N ^ 2). What's the correct answer and why?

My thought process is: (O (N ^ 2) + O (1)) + (O (N ^ 2) + O (1)) = O (N ^ 2)

thank

public static void zeroOut(int[][] matrix) { 
    int[] row = new int[matrix.length];
    int[] column = new int[matrix[0].length];
// Store the row and column index with value 0 
 for (int i = 0; i < matrix.length; i++)
   {
    for (int j = 0; j < matrix[0].length;j++) { 
       if (matrix[i][j] == 0) 
          {
            row[i] = 1;
            column[j] = 1; 
          }
   } 
  }
// Set arr[i][j] to 0 if either row i or column j has a 0 
for (int i = 0; i < matrix.length; i++)
 {
   for (int j = 0; j < matrix[0].length; j++)
      { 
        if ((row[i] == 1 || column[j] == 1)){
              matrix[i][j] = 0; 
           }
      } 
  }
}

      

+3


source to share


1 answer


What do M and N stand for? My guess is that it refers to "rows" and "columns" respectively. If so, then the equation is O (MN) because you are punching M a number of times.



O (N ^ 2) will be correct IF rows and columns.

+9


source







All Articles