• edited by
131 views

2 Answers

2 2 votes

The outer loop runs $n$ times.

The inner loop does not always run $n$ times. Its count depends on $i$.

$i = 0  \rightarrow$ inner loop runs $n - 1$ times
$i = 1  \rightarrow$ inner loop runs $n - 2$ times
$i = 2  \rightarrow$ inner loop runs $n - 3$ times
$...$
$i = n-1 \rightarrow$ inner loop runs $0$ times

Total work is:

$(n - 1) + (n - 2) + ... + 1 + 0$
$= n(n - 1)/2$
$= \mathrm{O(N^2)}$

Therefore, the Big-O efficiency is $\mathbf{O(N^2)}$.

Correct Option: D

• edited by
0 0 votes
def f1(n):
    ret = []
    for i in range(n):              # runs n times
        for j in range(i + 1, n):   # runs n-i-1 times
            ret.append(i + j)       # has cost O(1)
    return ret

So we end up with

$\sum_{i=0}^{n-1} (n-i-1) = \sum_{i=0}^{n-1} (i) = \frac{n(n-1)}{2} = O(N^2)$.

Answer:
Position:
Show:

Related questions

3 3 votes
2 2 answers
162
162 views
GO Classes asked Jul 6
162 views
Let $\text{L}$ contain $\text{N}$ items. What is the Big-O efficiency of the following function?def countSquares(L): count = 0 for item in L: square = item 2 if item != s...
1 1 vote
2 2 answers
124
124 views
GO Classes asked Jul 6
124 views
Describe the order of growth of the function below.def bonk(n): sum = 0 while n >= 2: sum += n n = n / 2 return sumConstantLogarithmicLinearQuadraticExponentialNone of th...
1 1 vote
2 2 answers
115
115 views
GO Classes asked Jul 6
115 views
What is the order of growth of $\texttt{foo}$ in terms of $\texttt{n}$, where $\texttt{n}$ is the length of $\texttt{lst}$?Assume slicing a list and calling $\texttt{len}...
1 1 vote
2 2 answers
129
129 views
GO Classes asked Jul 6
129 views
What is the order of growth of $\texttt{bar}$ in terms of $\texttt{n}$?def bar(n): i, sum = 1, 0 while i <= n: sum += biz(n) i += 1 return sum def biz(n): i, sum = 1, 0 w...