2
def f(n):
    if n < 100000:
        return 0;
    for(int i = 0; i < n*n; i++){
        return f(n-1)
    }

What is the time complexity?


My answer is $O((n!)^2)$. Here's my thought process:

  1. The for loop will be running $n^2$ the first time.

  2. However, during the first loop (i.e., $i = 0$), it will call $f(n-1)$, hence the next for loop will be $(n-1)^2$.

  3. This will keep going until $n <10000$ (base case). Assuming $n$ is very huge, the number of calls for each function to base case is essentially $n$ times.

  4. Now, considering all the for loops, the total number of calls is essentially $n^2 \cdot (n-1)^2 \cdot (n-2)^2 \cdots 1!$ (there will be a total of $n$ times multiplication, and each multiplication will be $n-1$ of the previous one because of $f(n-1)$ call).

89f3a1c
  • 123
  • 8

1 Answers1

4

It runs in time $O(n)$. Remember that a function only returns once. In each call to f, the for loop is immediately terminated at i=0 by the return statement, so the function body is equivalent to

if n < 100000
    return 0;
else
    return f(n-1);

However, your answer of $O((n!)^2)$ is not wrong: $(n!)^2$ is a huge overestimate of the running time, but big-$O$ essentially means "at most this much."

David Richerby
  • 81,689
  • 26
  • 141
  • 235