0

I recently came across this interview question, Matrix largest product of n numbers in a row

I understood the rolling multiplication approach. I wanted to know if there would be any further optimization possible if I bounded the problem making it compulsory to select the entire row, column or diagonal.

So basically the question now becomes, Given an NxM matrix, find the row or column or diagonal with the largest product.

Is there an O(log n) algorithm possible?

Community
  • 1
  • 1
Adwait Kumar
  • 1,552
  • 10
  • 25

2 Answers2

1

NO,If you matrix is N X M in worst case you can't do any better than O(NM) because you have to find the product of all rows, columns as well as diagonals.You can not avoid these calculation.

You can do small optimizations like removing the rows/columns/diagonals where there are zeroes(since the multiplication will result in a zero)

Community
  • 1
  • 1
Karthik
  • 4,950
  • 6
  • 35
  • 65
1

You have to look at least once at each row and each column, so you can't do better than O(max(M, N)). For simplicity many consider M == N and represent this as O(N).

Since you also need to look at each element in a row / column, this makes it O(M*N). Essentially what this indicates is that you need to look at every element of the matrix before arriving at the result.

user1952500
  • 6,611
  • 3
  • 24
  • 37