What is the time complexity of the following code. Explain what the following code does

Assume below that when the method is called, n is the number of rows; and m is the number of columns.

public class TimeComplexity

public static int sum(double[] data, int n, int m) {

int i; // for the row index
int j; // for the column index
double sum = 0;

for (i = 0; i < n; i++) {
	for (j = i; j < i + 2 && j < m + 2;j++) {
		sum += a[i][j]
    	}
 }
return sum;

}

Answer is: Time complexity of above program is:
n*(m+2)(m+3)/2
i.e. n
m^2

Time complexity of above program is O(n*min(2,m)). Why min(2,m) ?
Because code inner loop execute till j<min(2,m) in worst case.

1 Like
//