What is the time complexity?
def total(nums):
s = 0
for x in nums:
s += x
return sOptions
- O(1)
- O(n) (Correct option)
- O(n²)
- O(log n)
Answer
O(n)
Why
The loop runs once for each of the n items, and each iteration does a constant amount of work (one addition).
n iterations × constant work = O(n), called linear time: double the list, double the time.
Remember
One loop over n items = O(n).