GeeksforGeeks » Algorithms
TIME COMPLEXITY PROBLEM
(4 posts)-
What will be the time complexity T(n) and space complexity S(n) of the following Algorithm?
How can we build a recursion tree for the same?Large(n) { If(n<=1) Return n;' Sum = 0; For i= 1 To n-1 Sum = Sum + Large(i); Return Sum; } -
T(n) = Sum of T(i) for i = 1 to n - 1 + C
Where C is constant for operations other than recursive calls.
The recursion tree will look like following:
Step 1: C / | ...\ T(n-1) T(n-2) T(1)Step 2: C / | \ / | \ C C ... C / | .. \ /..\ T(n-2) T(n-1)..T(1)Recursion tree method doesn't seem very helpful here to find the complexity. You can find the complexity by considering base cases one by one
T(1) = C
T(2) = T(1) + C = 2C
T(3) = T(2) + T(1) + C = 4C
T(4) = T(3) + T(2) + T(1) + C = 8C
T(5) = T(4) + T(3) + T(2) + T(1) + C = 16CYou can see that the complexity increases in powers of 2. So T(n) would be O(2^n)
-
Thanks. But what will be the space complexity?
-
space complexity is O(n).
Reply
You must log in to post.