Big-O for traversing perimeter of 2D array

Viewed 31

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?

0 Answers
Related