2

I don't understand why the complexity of res = res + res is O(n). In this code res doubles its size in each iteration, thus the complexity of this line is changing with each iteration as follows:

2 + 4 + 8 + ... + n = O(n)

I'm confused about why this series equal to O(n).

def ones (n): # complexity O(n)
    res = [1] # 1 = O (1)
    while len ( res ) < n: # 1 + 1 ... + 1 ( log n times ) = O(log n)
        res = res + res # 2 + 4 ... + n = O(n) Why this is O(n)
    return res # 0 = O (0)

1 Answers1

0

The complexity of doubling size of the list that will never be larger than N is O(N), however, since you do that in a loop which repeats logN times, the overall complexity of your function will be O(NlogN).

I'd rather recommend a linear solution, like:

def ones(n) :
    return [1] * n
lenik
  • 23,228
  • 4
  • 34
  • 43