Big O notation O(NM) or (N^2)
I've been told the below code is = O(MN) however, I come up with O(N^2). Which is the correct answer and why?
My thought process: nested for loops plus if statements --> (O(N^2)+O(1)) + (O(N^2)+O(1)) = O(N^2)
Thank you
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;
}
}
}
}
Solution 1:
What does M and N refers to? My assumption is that it refers to "rows" and "columns" respectively. If it is so, then the equation is O(MN) because you loop through M number of N times.
O(N^2) will be correct IF rows and columns are equal.