0

What are the time complexities of the following code? I posted this on the general stackexchange website, but it was suggested that I post it here.

def func(n):
    for _ in range(n):
        if n == 4:
            for _ in range(n):
                <O(1) operation>

It will only be O(n^2) for one specific input (n = 4) but is O(n) for all other inputs. In this case the worst case is obviously O(n^2), yet my instructor says that O(n) is the correct answer. If "big-Oh" notation is to indicate the worst case scenario, why is it not O(n^2)?

Another one is:

def func2(n):
    for _ in range(n):
        if n%2 == 0:
            for _ in range(n):
                <O(1) operation>

I am not so certain about the run time of this piece of code. Again, worst case is O(n^2). This time half of all possible inputs results in the worst case. Would this suffice in saying that the code runs in O(n^2) time?

If the first part is O(n) and the second part is O(n^2), is there a general rule of thumb when you choose the truly worst case for the "big-Oh" representation?

Raphael
  • 72,336
  • 29
  • 179
  • 389
  • We have quite a number of similar questions (cf [tag:algorithm-analysis+loops]): translate loops to sums and you are fine. Also, read up on what Landau symbols actually mean; you'll see that the sentence "I think it's $O(n^2)$ but they say it's $O(n)$, who's right?" is not very meaningful, since both can be right. (You probably want to use $\Theta$). Also, $O$ does not identify with worst-case. – Raphael Apr 01 '14 at 07:33
  • (PS: The "general stackexchange" probably means [SO], which is all but general. This is definitely the right place for such questions; it's just that we have answered it multiple times already.) – Raphael Apr 01 '14 at 07:44

0 Answers0