Big O - Code Complexity

110 Views Asked by At

I am working with Big O and I got this exercise I am working on.

The Exercise

I know the first line is running in constant time. But I am confused on how to measure the while-loop.

2

There are 2 best solutions below

3
On

The outer loop runs $n$ times.

The inner runs $n-i-1$ times, and since $i \le n$, it runs at most $n$ times.

Therefore, the total is at most $n\cdot n = n^2$.

Actually, it is $n^2/2+O(n)$, but $O(n^2)$ is enough.

0
On

To think of it simply, each time that the outer loop runs, the other loop runs a maximum of n times. Since the outer loop runs n times, we will have n^2 runs, and so the complexity is quadratic.