Saturday, March 3, 2018

O(n) for matrices

Recently, I was discussing a coding problem with a couple of developers.
"Transpose a nxn matrix along it's diagonal"
I won't tell you the answer to the problem because you are all masters and of course it is very easy for you to figure it out (or search it!). But this problem ignited a discussion among us about O(n) for matrices.

So if you traverse a two dimensional matrix array[n][n] using two loops as follows:
for(i=1 to n)
for(j=1 to n)
print array[i][j]
What is the efficiency of the above algorithm?
You might be tempted to say it is O(n2) since we have two for loops. But look closer. The number of elements in a nXn matrix is n2. And therefore the efficiency of above algorithm is O(N) where N (=n2) is the number of elements in the matrix.

No comments:

Post a Comment