Repaso
Español
Algorithms & DSCoreALG-39

What is the time complexity?

def total(nums):
    s = 0
    for x in nums:
        s += x
    return s

Options

  1. O(1)
  2. O(n) (Correct option)
  3. O(n²)
  4. 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).

Key terms

Practice this question in Repaso