Given the code below and the comment analysis:
n = len(L) # O(1)
for i in range(n): # O(n) - I read online that range(n) will take constant time
but the 'for i in range(n)' part would make this O(n)?
if L[i] > 0 : # O(1)
for j in range(n): # O(n)
answer = answer + L[i] # O(1) - since indexing takes constant time
else : # O(1)
for j in range(n): # O(n)
answer = answer - L[i] # O(1)
My Overall Analysis:
- $O(1)$ for the first variable assignment
- first if statement takes overall $O(n)$
- else statement also takes overall $O(n)$ => Overall if/else statements take $O(n)$ as well
- for loop iterates n times => $O(n * n)$ => $O(n^2)$
=> Overall time complexity $O(n^2)$
Thanks in advance for the suggestions!
EDIT: I am wondering if the
for i in range(n)
portion of the code takes O(n) or O(1)? I read that range(n) would take O(1) but since its a for loop it would take O(n)?
range
and so on, which is off-topic, here. – David Richerby Apr 18 '19 at 21:20