Below is some pseudocode I wrote that, given an array A and an integer value k, returns true if there are two different integers in A that sum to k, and returns false otherwise. I am trying to determine the time complexity of this algorithm.
I’m guessing that the complexity of this algorithm in the worst case is O(n^2). This is because the first for loop runs n times, and the for loop within this loop also runs n times. The if statement makes one comparison and returns a value if true, which are both constant time operations. The final return statement is also a constant time operation.
Am I correct in my guess? I’m new to algorithms and complexity, so please correct me if I went wrong anywhere!
Algorithm ArraySum(A, n, k)
for (i=0, i<n, i++)
for (j=i+1, j<n, j++)
if (A[i]+A[j]=k)
return true
return false
Azodious’s reasoning is incorrect. The inner loop does not simply run
n-1times. Thus, you should not use(outer iterations)*(inner iterations)to compute the complexity.The important thing to observe is, that the inner loop’s runtime changes with each iteration of the outer loop.
It is correct, that the first time the loop runs, it will do
n-1iterations. But after that, the amount of iterations always decreases by one:We can use Gauss’ trick (second formula) to sum this series to get
n(n-1)/2 = (n² - n)/2. This is how many times the comparison runs in total in the worst case.From this, we can see that the bound can not get any tighter than
O(n²). As you can see, there is no need for guessing.Note that you cannot provide a meaningful lower bound, because the algorithm may complete after any step. This implies the algorithm’s best case is
O(1).