Question

Why does the below function have a time complexity of O(n)? I can't figure it out for the life of me.

void setUpperTriangular (
    int intMatrix[0,…,n-1][0,…,n-1]) {
        for (int i=1; i<n; i++) {
            for (int j=0; j<i; j++) {
                    intMatrix[i][j] = 0;
            } 
        }
    }
}

I keep getting the final time complexity as O(n^2) because:

i: execute n times{//Time complexity=n*(n*1)
    j: execute n times{ //Time complexity=n*1
        intMatrix[i][j] = 0; //Time complexity=1
    }
}
Was it helpful?

Solution

The code iterates through n^2/2 (half a square matrix) locations in the array, so its time complexity is O(n^2)

OTHER TIPS

This is same as insertion sort's for loop. Time complexity of insertion sort is O(n2).

So, CS department head explained it a different way. He said that since the second loop doesn't iterate n times, it iterates n! times. So technically it is O(n).

It can be at most considered as O(n.m) which finally comes down to O(n.n) or O(n^2)..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top