0

I want to understand what and how to calculate the time complexity of this algorithm given in pseudocode below. I suspect the T.C is O(n) since there is a loop iterating through the entire list but I'm not sure or is it O(n^2) since in every loop the search function of lists is also called? But also generally how to calculate time complexities of given algorithms. Thank you in advance.

for i = 0 to n-1
    Add the numbers A[0] thru A[i]
    Store the result in B[i]
erkoo
  • 23
  • 5
  • [Try this...](https://stackoverflow.com/questions/11032015/how-to-find-time-complexity-of-an-algorithm) – Henri Apr 01 '20 at 22:41
  • Yeah, thank you I read it earlier but did not feel really sure. But based on that post, the time complexity should, I feel, be O(n) with the loop executing n times but is the search of the list index not impacting the time? – erkoo Apr 01 '20 at 22:46

1 Answers1

0

The running time of the algorithm you have is O(n^2). In the second line you are summing A[0] to A[i]. So the loop iterates n times. In the first iteration you are adding A[0], then A[0] + A[1], then A[0] + A[1] + A[2] and so on.

So in general on iteration i you are adding i numbers. So the running time would be:

1 + 2 + 3 + ... + n

This is the sum of the first n numbers which evaluates to n(n+1)/2: https://brilliant.org/wiki/sum-of-n-n2-or-n3/

In general, not every line inside a loop is constant time. Try to look at what happens for each line at a few different iterations of the loop to get an idea of what is going on. If it changes in each iteration then it is not constant.

There is however an O(n) algorithm where you simply increment a sum variable:

sum = 0
for i = 0 to n - 1:
    sum += A[i]
    B[i] = sum

In this case, at the start of iteration i, sum already stores the sum of A[0] to A[i-1] so to get the sum of A[0] to A[i] simply add A[i]

mattyx17
  • 806
  • 6
  • 11