0

I'm trying to analyze an algorithm that looks like this:

def foo(L):
    for n in L:
        for x in range(n):
            ...

What would be its time complexity? First I thought $O(n)$, where $n$ is the number of elements in $L$, but that seems a little optimistic given that numbers can become very large. Then I thought $O(n^2)$ but that seem quite arbitrary too. $O(nm)$ where $m$ is the maximum value in $L$ perhaps?

Raphael
  • 73,212
  • 30
  • 182
  • 400

1 Answers1

1

Your result of seems correct, assuming none of the omitted operations modify the values of the variables n, L or x.

For a fixed value $k$ of n, the inner loop (for x in range(n):) loops over the set (or list; it is irrelevant for the analysis) $\{ 0, \dots, k - 1\}$, which contains $k$ elements. The outer loop (for n in L:) simply loops over each element of $L$ for a total of $|L|$ iterations, $|L|$ being the length of $L$. Thus, assuming the omitted operations are executed in $O(1)$ time, we obtain a time complexity of $O(m|L|)$ (as you propounded), where $m$ is the maximum value in $L$.

Incidentally, if you know the average value for the elements of $L$ you could also use the above reasoning to derive the average time complexity as well. (Just plug in the average value for $k$.)


As pointed out by @Raphael in the comments, of course, there is plenty of room for improvements if more assumptions are made about the contents of $L$.

dkaeae
  • 5,057
  • 1
  • 17
  • 31