2

Suppose I have a m x n array and want to perform an operation on just its perimeter as follows:

for(let i = 0; i < m; i++){
  for(let j = 0; j < n; j++){
    if(i * j === 0 || i === m - 1 || j === n - 1){
      // some function that has O(m * n) time complexity
    }
  }
}

My calculation for the (worst case) time complexity is:

O(top + right + bottom + left)
= O(2*top + 2*right)
= O(2*top) + O(2*right)
= O(top) + O(right)
= O(n * m * n) + O(m * m * n)
= O(m * n^2) + O(n * m^2)

Is this correct, or am I missing something?

lbragile
  • 7,549
  • 3
  • 27
  • 64
  • Correct. For me I'd calculate it as `O(m + n) * O(m * n)=O((m+n) * mn)`. (the perimeter * the inner time complexity) – Haoliang Jun 19 '22 at 03:17
  • Oh yeah, good point - that is more intuitive. – lbragile Jun 19 '22 at 03:21
  • Notice that you are still looping through `m*n` cells when you could loop through just `m+n`. The time complexity in this case happens to be the same (`O(m*n) + O((m+n)*m*n) = O((m+n)*m*n)`), but in general there is no need to loop through all the cells (`O(m*n)`) if you just need the perimeter (`O(m+n)`). – Berthur Jun 20 '22 at 10:53

0 Answers0