1
$\begingroup$
fun(int n)
{
    if (n == 1)
       S1 // S1 takes O(N) time
    else 
       S2 + fun(n-1) // S2 takes O(1) time
}

What can be said about the time complexity of given Code snippet ?


I think the recurrence equation can be written as $T(N) = T(N-1) + N$ and this says Time complexity = $O(N^2)$

But I am not sure about this ?

  • 0
    Which language? In C, you get undefined behaviour on calling `fun(3)` for example.2017-01-05
  • 0
    @DanielFischer, I am just interested in recurrence equation for such problems .2017-01-05
  • 0
    @DanielFischer,Is my recurrence correct in case "The statement inside IF block takes O(N) time " ?2017-01-05
  • 0
    The problem is that not all inputs lead to a predictable recurrence. If we use hypothetical truly mathematical integers, you get an infinite loop for inputs $< 4$.2017-01-05
  • 0
    @DanielFischer I have tried to ease the code !! Can you please check Now ?2017-01-05
  • 0
    Oops, you only go inside the `if` for one particular value of `n`, so it doesn't make sense to speak of $O(n)$ for that, and that work is only done once. But you still have the problem that inputs $\leqslant 0$ aren't well-behaved.2017-01-05

1 Answers 1

2

It is linear in $N$. The recurrence is $T(n) = T(n-1)+C$ with $T(4)$ being a constant, since you do a constant amount of work (the if statement, and then the return) at each step before calling the recursion.

  • 0
    What will be recurrence in case "The statement inside IF block takes O(N) time " ?2017-01-05
  • 1
    Surely it would still be O(n). The function fun(n) is O(n) (for n > 1) since it does n-1 recursive calls to itself, and S1 is O(n) and is done exactly 1 time. O(n) + O(n) (in informal terms) is still O(n).2017-01-05