Home > Back-end >  What is the time complexity of this function? (nested for loop)
What is the time complexity of this function? (nested for loop)

Time:06-05

I think it's O(n * m) but also think its O(n)

Can't really tell which one is correct..

Considering first loop only loops 20 times (fixed amount), and second nested for loop only loops number / 20, and lastly third nested loops 3 times.

So it comes out as O(n * m / 20 * 3) which we can call it as O(n * m * k)? is this correct?

or it's O(n) because the second loops time complexity will only effect it since it's different depending on what the user inputs as number.

function loop(number) {
  let answer = 0;

  for (let i = 0; i < 20; i  ) {
    for (let j = 0; j < number / 20; j  ) {
      for (let k = 0; k < 3; k  ) {
        answer  ;
      }
    }
  }

  return answer;
}

CodePudding user response:

The outer loop always loops exactly 20 times, the inner loop always loops exactly 3 times. The only one that has any variability is the middle loop, which loops number / 20 times. So you will be incrementing answer 20 * 3 * (n / 20) times, and since constants are ignored for Big O notation, this works out to O(N).

CodePudding user response:

In this case the time complexity is O(n·m·k) or in your code variables O(i·j·k) and can be simplified as O(n)^3 (cubic) in the general case.

Being specific, 20*(number/20) * 3 operations will be carried out

  • Related