1

Imagine a scenario where the second loop is iterated once for each iteration of n except the last one where it is iterated m times:

// n and m are two different variables.
for(int i=0; i<n; i++) {
  for(int j=0; j<m; j++) {
    if(i!=(n-1)) break;

    // O(1) code here.
  }
}

What would be the time complexity of this? Is it O(n*m), O(n+m) or something else?

Monke
  • 35
  • 9

1 Answers1

1

EDIT: original answer was wrong based on a misread.

This is O(n + m) because for n - 1 iterations of the outermost loop, a constant amount of work is done: it starts the inner loop and aborts on the first iteration. For the last iteration of the outermost loop, the innermost loop iterates m times, doing a constant amount of work each iteration. So, we have (n - 1) * x + 1 * (m * y) total steps, where x and y are some constants. And we know that (n - 1) * x + 1 * (m * y) = O(n + m) since we can drop the constant factors on our independent variables n and m.

Patrick87
  • 25,592
  • 3
  • 33
  • 69
  • Correct me if I'm wrong, isn't the "break" inside the second loop should be "continue" in order to increment j by m for each value of n? Since its break, the second loop should iterate once and then exit (except where i=n-1). – Monke May 08 '20 at 11:53
  • 1
    @ErenKara You're right, I read this wrong; for whatever reason I read the `if` condition as being based on `j`, not `i`. I will update the answer. – Patrick87 May 08 '20 at 11:59