-2

Here Nested loops are used, the time complexity of outer loop will be O(n) but how to calculate the complexity of inner loop as it depends on the value of i Here Nested loops are used, the time complexity of outer loop will be O(n) but how to calculate the complexity of inner loop as it depends on the value of i

1 Answers1

1

Both inner and outer loop are $O(n)$, and the total time complexity is $O(n^2)$. This is because the inner loop will make at most $2*n$ steps which is clearly $O(n)$.

The loop will make $$2\cdot1 + 2\cdot 2 + 2\cdot 3 + 2\cdot 4 + \dots + 2 \cdot n = \\ 2(1 + 2 + \dots + n) = \\ 2(\frac{n\cdot(n+1)}{2}) = \\n \cdot (n+1) = O(n^2)$$

someone12321
  • 1,428
  • 15
  • 27