1 1 vote Let $\text{N = n}$. What is the Big-O efficiency of the function below?def f1(n): ret = [] for i in range(n): for j in range(i + 1, n): ret.append(i + j) return ret$\mathrm{O(\log N)}$$\text{O(N)}$$\mathrm{O(N \log N)}$$\mathrm{O(N^2)}$ Algorithms goclasses goclasses-da-dpp goclasses-da-dpp-day-217 python-&-dsa goclasses-python-&-dsa-practice-questions time-complexity + – GO Classes 131 views answer comment Share Follow Print 0 reply Please log in or register to add a comment.
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$ timesTotal 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 GO Classes answered Jul 6 • edited Jul 6 by GO Classes GO Classes comment Share Follow 0 reply Please log in or register to add a comment.
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 retSo 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)$. Meticulous_March answered Jul 6 Meticulous_March comment Share Follow 0 reply Please log in or register to add a comment.